你应该如何使用带有PathShape的ShapeDrawable在自定义视图上绘制一条线?

时间:2012-07-15 21:56:32

标签: android path line custom-view shapedrawable

我正在尝试在自定义View中绘制一条线。在这里,我创建了一个只有一个段的简单Path,从中创建了一个PathShape,最后将其粘贴到ShapeDrawable中,目的是使用它来绘制{在Canvas内{1}}。但是,这不起作用。看看我的例子,这里。

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()也不使用PathShapeShapeDrawable实际绘制到Path上作品。我尝试的时候什么都没画。有谁知道为什么?

我正在测试的设备是运行Android 4.1.1。

1 个答案:

答案 0 :(得分:12)

这有两个问题。

第一种是Paint风格。默认值为Paint.Stroke.FILL,但如果有一行则无法填充。我需要添加这个(谢谢,Romain Guy):

this.mPaint.setStyle(Paint.Style.STROKE);

第二个问题是PathShape中的标准高度和宽度不正确。我已经阅读了the documentation,但没有正确理解。一旦我解决了第一个问题,这就变得明显了。将它设置为我的自定义视图的高度和宽度(因为我正在绘制整个视图)修复了这个问题。我还必须更改ShapeDrawable的界限才能匹配。

this.mPathShape = new PathShape(this.mPath, this.getWidth(), this.getHeight());

this.mShapeDrawable.setBounds(0, 0, this.getWidth(), this.getHeight());

希望将来可以帮助其他人。