I am trying to make a string in custom View. Here I created a simple Pathone with only one segment, created from it PathShapeand finally put it in ShapeDrawablewith the intention of using it to draw Canvasinside onDraw(), however this does not work. See my example here.
package com.example.test;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.PathShape;
import android.util.Log;
import android.view.View;
public class TestView extends View {
private Path mPath = null;
private Paint mPaint = null;
private PathShape mPathShape = null;
private ShapeDrawable mShapeDrawable = null;
public TestView(Context context) {
super(context);
}
private void init() {
int width = this.getWidth() / 2;
int height = this.getHeight() / 2;
Log.d("init", String.format("width: %d; height: %d", width, height));
this.mPath = new Path();
this.mPath.moveTo(0, 0);
this.mPath.lineTo(width, height);
this.mPaint = new Paint();
this.mPaint.setColor(Color.RED);
this.mPathShape = new PathShape(this.mPath, 1, 1);
this.mShapeDrawable = new ShapeDrawable(this.mPathShape);
this.mShapeDrawable.getPaint().set(this.mPaint);
this.mShapeDrawable.setBounds(0, 0, width, height);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
this.init();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Log.d("onDraw", "Drawing");
canvas.drawLine(0.0f, 0.0f, this.getWidth() / 2.0f, this.getHeight() / 2.0f, this.mPaint);
}
}
As you can see from my comments in the method onDraw(), using PathShapeand ShapeDrawablefor drawing Pathon Canvasdoes work. When I try, nothing is drawn. Does anyone know why?
The device I'm testing this on is running Android 4.1.1.
source