Android drawArc弧形不规则

时间:2015-02-27 12:46:25

标签: android canvas draw

Illustration

我使用相同的RectF绘制弧的多个段,但是弧不能正确排列。我尝试了所有CAP选项,但它看起来从不对称。

 private void initPaint(TypedArray a){

    segmentInactivePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    segmentInactivePaint.setColor(a.getColor(R.styleable.SegmentsCustomView_segmentBgColor, segmentBgColor));
    segmentInactivePaint.setStrokeWidth(30f);
    segmentInactivePaint.setStyle(Paint.Style.STROKE);

    segmentsBGPaint = new Paint(segmentInactivePaint);
    segmentsBGPaint.setAlpha(64);

    segmentActivePaint = new Paint(segmentInactivePaint);
    segmentActivePaint.setColor(a.getColor(R.styleable.SegmentsCustomView_segmentActiveColor,segmentActiveColor));

}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    if(getWidth()<getHeight()) {
        rectF.set(getLeft(), getTop(), getWidth() - getLeft(), getWidth() - getLeft());
    }else{
        rectF.set(getLeft(), getTop(), getHeight() - getTop(), getHeight() - getTop());

    }
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    position = 0;
    for(int i=0; i < segmentSizes.length; i++){
        canvas.drawArc(rectF,position-180,segmentSizes[i]-segmentGap,false,
                i != segmentActive ?
                            i < segmentActive ? segmentInactivePaint :  segmentsBGPaint
                        : segmentActivePaint);
        position+=segmentSizes[i];
    }

}

我也尝试使用静态RectF,任何调整大小事件都不会改变它,所以这不是问题。

RectF (0):﹕ [75.0,75.0][759.0,759.0]
RectF (1):﹕ [75.0,75.0][759.0,759.0]
RectF (2):﹕ [75.0,75.0][759.0,759.0]
RectF (3):﹕ [75.0,75.0][759.0,759.0]
RectF (4):﹕ [75.0,75.0][759.0,759.0]

我的猜测是,Canvas.drawArc方法会创建一个部分路径,因此弧的插值总是与整圆的弧不同。

非常感谢向正确的方向发展。

1 个答案:

答案 0 :(得分:0)

所以我设法通过使用Path而不是画布的drawArc()方法来解决问题。通过在绘制新段时重绕路径。

 @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        position = 0;
        for(int i=0; i < segmentSizes.length; i++){
            if(i == segmentActive){
                tmpPaint = segmentActivePaint;
            }else if(i > segmentActive){
                tmpPaint = segmentsBGPaint;
            }else{
                tmpPaint = segmentInactivePaint;
            }

            path.rewind();
            path.addArc(rectF,position - 180, segmentSizes[i] - segmentGap);
            canvas.drawPath(path, tmpPaint);
            position+=segmentSizes[i];
        }
        path.reset();

    }

无论子弧的数量如何,倒带似乎都能画出近乎完美的圆圈。

drawArc()方法似乎与addArc()非常相似,但它会在每次调用时重置路径。