gpt4 book ai didi

android - 您应该如何使用带有 PathShape 的 ShapeDrawable 在自定义 View 上绘制线条?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:03:13 25 4
gpt4 key购买 nike

我正在尝试在自定义 View 中画一条线。在这里,我创建了一个只有一个段的简单 Path,从中创建了一个 PathShape,最后将其插入到一个 ShapeDrawable 中 Intent 使用它在 onDraw() 内的 Canvas 上绘制。但是,这不起作用。请在此处查看我的示例。

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。

最佳答案

这有两个问题。

第一个是Paint 样式。默认是 Paint.Stroke.FILL,但是用一条线没有什么可以填充的。我需要添加这个(谢谢,Romain Guy):

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

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

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

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

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

关于android - 您应该如何使用带有 PathShape 的 ShapeDrawable 在自定义 View 上绘制线条?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11495953/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com