我正试图在自定义View中画一条线。在这里,我创建了一个简单的Path,只有一个片段,从中创建了一个PathShape,最后将其插入到一个ShapeDrawable中,目的是利用这个来绘制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()方法中的注释可以看出,使用PathShapeShapeDrawablePath绘制到Canvas上实际上都不起作用。当我尝试的时候什么也画不出来。有人知道为什么吗?
我正在测试的设备运行的是android 4.1.1。

最佳答案

这有两个问题。
第一种是Paint风格。默认值是Paint.Stroke.FILL,但是有一行就没有要填充的内容。我需要加上这个(谢谢,Romain Guy):

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

第二个问题是PathShape中的标准高度和宽度不正确。我读过这篇文章,但没有正确理解。一旦我解决了第一个问题,这就变得很明显了。将其设置为自定义视图的高度和宽度(因为我正在绘制整个视图)修复了此问题。我还必须更改ShapeDrawable的边界才能匹配。
this.mPathShape = new PathShape(this.mPath, this.getWidth(), this.getHeight());


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

希望这对将来的其他人有帮助。

08-04 18:49