我正在尝试在 custom 中画一条线View
。在这里,我创建了一个Path
只有一个片段的简单片段,PathShape
从中创建了一个,最后将其粘贴到 aShapeDrawable
中,目的是使用它在Canvas
内部绘制onDraw()
。但是,这不起作用。看我的例子,在这里。
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);
// Doing this here because in the constructor we don't have the width and height of the view, yet
this.init();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Log.d("onDraw", "Drawing");
// This works, but won't let me do what I'm really trying to do
canvas.drawLine(0.0f, 0.0f, this.getWidth() / 2.0f, this.getHeight() / 2.0f, this.mPaint);
// This should work, but does not
//this.mPathShape.draw(canvas, this.mPaint);
// This should work, but does not
//this.mShapeDrawable.draw(canvas);
}
}
从我在onDraw()
方法中的评论中可以看出,既不使用PathShape
也不使用ShapeDrawable
将 绘制Path
到Canvas
实际作品上。当我尝试时,什么都没有画出来。有谁知道为什么?
我正在测试的设备运行的是 Android 4.1.1。