在 canvas 上绘图时路径弧比线弧粗

Path arc is thicker than line arc when drawing on canvas

我正在创建一个自定义视图,它使用 canvas 绘制了一条带有圆角的简单线条,但我无法让拐角处的线条与直线部分具有相同的粗细。 路径在onSizeChanged方法中定义。

我的观点是这样的:

这是风景

public class CanvasView extends View {

private Bitmap mBitmap;
private Canvas mCanvas;
private Path mPath;
private Paint mBitmapPaint;
Context context;

public CanvasView(Context c) {
    super(c);
    context = c;
    mPath = new Path();
    mBitmapPaint = new Paint(Paint.DITHER_FLAG);
}

public CanvasView(Context c, AttributeSet attrs) {
    super(c, attrs);
    context = c;
    mPath = new Path();
    mBitmapPaint = new Paint(Paint.DITHER_FLAG);
}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    if(mBitmap == null) {

        RectF rectf = new RectF(w - w / 2, h - w / 2, w, h);
        mPath.moveTo(w, 0);
        mPath.lineTo(w, h - w / 2);
        mPath.arcTo(rectf, 0, 90);
        mPath.lineTo(0, h);

        mBitmapPaint.setAntiAlias(true);
        mBitmapPaint.setDither(true);
        mBitmapPaint.setColor(context.getResources().getColor(R.color.siminn_warm_gray));
        mBitmapPaint.setStyle(Paint.Style.STROKE);

        mBitmapPaint.setStrokeWidth(5);
    }
}


@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
    canvas.drawPath(mPath, mBitmapPaint);

}
}

我想出来了,我是沿着 canvas 的边缘画的,结果只显示了一半的线。我将线条从边缘移了一点,效果很好

当您使用 canvas 绘图时,您必须考虑视图填充。 onSizeChanged 方法为您提供没有填充的视图的宽度和高度。要获得填充,您可以在视图 class 中使用 getPaddingTop()getPaddingBottom()getPaddingStart()getPaddingEnd() 函数。 这将是考虑填充的代码:

@Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        int realWidth = w - (getPaddingStart() + getPaddingEnd());
        int realHeight = h - (getPaddingTop() + getPaddingBottom());

        if (mBitmap == null) {
            RectF rectf = new RectF(realWidth - realWidth / 2, realHeight - realWidth / 2, realWidth, realHeight);
            mPath.moveTo(realWidth, getPaddingTop());
            mPath.lineTo(realWidth, realHeight - realWidth / 2);
            mPath.arcTo(rectf, 0, 90);
            mPath.lineTo(getPaddingStart(), realHeight);

            mBitmapPaint.setAntiAlias(true);
            mBitmapPaint.setDither(true);
            mBitmapPaint.setColor(context.getResources().getColor(R.color.siminn_warm_gray));
            mBitmapPaint.setStyle(Paint.Style.STROKE);
            mBitmapPaint.setStrokeWidth(5);
        }
    }