如何在画布中围绕圆圈制作可用的填充空间(Android)

时间:2013-11-02 20:06:03

标签: java android android-canvas

我在圆圈的外圈上显示有问题。当一个点放在圆的一个边缘时,点被切掉一半。屏幕截图:https://drive.google.com/file/d/0B9BaYaKRY3v3Y2hXYkpSOE1nY28/edit?usp=sharing

我只是想让圆形半径变小,这样它周围就有一些空间,外面的圆点有一些空间。当然圆圈仍然必须留在视图的中间。 Tipps如何做到这一点非常感谢。

工作代码打击完全正常工作,接受点被切断的事实。 (感谢@Sherif elKhatib提供有关创建双色圆圈的帮助)

public class PercentView extends View {

public PercentView(Context context) {
    super(context);
    init();
}

public PercentView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

public PercentView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init();
}

private void init() {
    paint = new Paint();
    paint.setColor(Color.parseColor("#3498db"));
    paint.setAntiAlias(true);
    paint.setStyle(Paint.Style.FILL);
    bgpaint = new Paint();
    bgpaint.setColor(Color.parseColor("#2980b9"));
    bgpaint.setAntiAlias(true);
    bgpaint.setStyle(Paint.Style.FILL);
    rect = new RectF();
    circlePaint = new Paint();
}

Paint paint;
Paint bgpaint;
RectF rect;
float percentage = 5;
Paint circlePaint;
float[] dots = new float[1000];
int dotsNum = -1;
String[] colorCode = new String[1000];

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    // draw background circle anyway
    canvas.drawArc(rect, -90, 360, true, bgpaint);
    if (percentage != 0) {
        int left = 0;
        int width = getWidth();
        int top = 0;
        rect.set(left, top, left + width, top + width);
        canvas.drawArc(rect, -90, (float) (3.6 * percentage), true, paint);

        for (int i = 0; i <= dotsNum; i++) {
            circlePaint.setAntiAlias(true);
            circlePaint.setColor(Color.parseColor(colorCode[i]));
            circlePaint.setStyle(Paint.Style.FILL);
            float dotX = (float) (this.getWidth() / 2 + this.getWidth() / 2
                    * Math.cos((dots[i] * 3.6 - 90) * Math.PI / 180));
            float dotY = (float) (this.getHeight() / 2 + this.getWidth()
                    / 2 * Math.sin((dots[i] * 3.6 - 90) * Math.PI / 180));
            canvas.drawCircle(dotX, dotY, 30, circlePaint);
        }
    }
}

public void setPercentage(float inpercentage) {
    this.percentage = inpercentage;
    invalidate();
}

public void setDot(int type) {
    dotsNum++;

    switch (type) {
    case 0: 
        colorCode[dotsNum] = "#27ae60";
        break;
    case 1: 
        colorCode[dotsNum] = "#f1c40f";
        break;
    case 2: 
        colorCode[dotsNum] = "#e74c3c";
        break;
    case 3: 
        colorCode[dotsNum] = "#34495e";
        break;
    }

    dots[dotsNum] = percentage;
    invalidate();
}

}

1 个答案:

答案 0 :(得分:0)

对我来说唯一的一种工作方法是那段代码“width = getWidth() - padding”。感谢@Catherine。