【问题标题】:Wrong Stroke width drawing circle on custom view Android自定义视图Android上错误的笔画宽度绘制圆圈
【发布时间】:2015-11-27 08:51:59
【问题描述】:

我正在 android 中编写自定义视图。我想画一个覆盖我视图所有宽度和高度的圆圈。这是我的代码

private void init() {

    bgpaint = new Paint();
    bgpaint.setColor(bgColor);
    bgpaint.setAntiAlias(true);
    bgpaint.setStyle(Paint.Style.STROKE);
    bgpaint.setStrokeWidth(strokeWidth);
    rect = new RectF();

}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    // draw background circle anyway
           int strokeWidth = 50;
    rect.set(strokeWidth, strokeWidth, getwidth()- strokeWidth, 
            getheight() - strokeWidth);
    canvas.drawArc(rect, -90, 360, fill, bgpaint);

}

但是当我运行结果会是这样的

我想要这样

我的代码有什么问题?

【问题讨论】:

  • 调用rect.set时必须使用strokeWidth / 2f,而不是strokeWidth

标签: android drawing android-custom-view


【解决方案1】:

问题在于设置矩形的坐标。您必须设置笔划宽度的一半,而不是整个笔划宽度。

    float left=strokeWidth / 2;
    float top=strokeWidth / 2;
    float right=minDimen - strokeWidth/ 2;
    float bottom=minDimen - strokeWidth / 2;
    rect.set(left, top, right,bottom);

因为涉及到圆形,我假设您的 circleView 的宽度和高度是相同的尺寸。那是我代码中的 minDimen 。因为我使用这两者中较小的尺寸。

final int minDimen = Math.min(width, height);
setMeasuredDimension(minDimen, minDimen);  

(必须在 onMeasure 方法中调用) 无论如何,将宽度和高度设置为相同尺寸的好方法。

【讨论】:

    猜你喜欢
    • 2013-12-23
    • 2013-10-02
    • 2013-11-25
    • 2021-06-30
    • 2014-11-15
    • 2014-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多