怎么是你应该使用ShapeDrawable与PathShape上绘制一个自定义视图行?(How ar

2019-07-30 10:38发布

我试图绘制自定义行View 。 在这里,我创建了一个简单Path只是一个单一的段,创造了一个PathShape从,终于坚持到这一个ShapeDrawable与使用对平局的意图CanvasonDraw() 但是,这是行不通的。 见我的例子,在这里。

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绘制PathCanvas实际工作。 当我尝试什么也不绘制。 有没有人有任何想法,为什么?

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

Answer 1:

没有与此两个问题。

首先是Paint风格。 默认值是Paint.Stroke.FILL ,但用一条线没有什么来填补。 我需要添加这个(感谢, 罗曼盖伊 ):

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());

希望这可以帮助别人,将来别人。



文章来源: How are you supposed to use a ShapeDrawable with a PathShape to draw a line on a custom View?