在一个视图中绘制一个最大的270度半圆形进度条,Android
时间: 2024-05-13 20:15:29 浏览: 50
Android带进度的圆形进度条
您可以使用 `Canvas` 和 `Path` 来绘制一个270度的半圆形进度条。以下是一个简单的示例代码:
```java
public class SemiCircleProgressBar extends View {
private Paint paint;
private RectF rectF;
private int progress = 0;
private int max = 100;
public SemiCircleProgressBar(Context context) {
super(context);
init();
}
public SemiCircleProgressBar(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public SemiCircleProgressBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
paint = new Paint();
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(10);
paint.setColor(Color.BLUE);
rectF = new RectF();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int desiredWidth = 200;
int desiredHeight = 200;
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int width;
int height;
//Measure Width
if (widthMode == MeasureSpec.EXACTLY) {
//Must be this size
width = widthSize;
} else if (widthMode == MeasureSpec.AT_MOST) {
//Can't be bigger than...
width = Math.min(desiredWidth, widthSize);
} else {
//Be whatever you want
width = desiredWidth;
}
//Measure Height
if (heightMode == MeasureSpec.EXACTLY) {
//Must be this size
height = heightSize;
} else if (heightMode == MeasureSpec.AT_MOST) {
//Can't be bigger than...
height = Math.min(desiredHeight, heightSize);
} else {
//Be whatever you want
height = desiredHeight;
}
//MUST CALL THIS
setMeasuredDimension(width, height);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int width = getWidth();
int height = getHeight();
int diameter = Math.min(width, height) - (int) (paint.getStrokeWidth() * 2);
rectF.set((width - diameter) / 2, (height - diameter) / 2, (width + diameter) / 2, (height + diameter) / 2);
Path path = new Path();
path.arcTo(rectF, 135, 270, true);
canvas.drawPath(path, paint);
float angle = 270 * progress / (float) max;
Path path2 = new Path();
path2.arcTo(rectF, 135, angle, true);
paint.setColor(Color.RED);
canvas.drawPath(path2, paint);
}
public int getProgress() {
return progress;
}
public void setProgress(int progress) {
this.progress = progress;
invalidate();
}
public int getMax() {
return max;
}
public void setMax(int max) {
this.max = max;
invalidate();
}
}
```
在 `onDraw()` 方法中,首先绘制一个最大的270度半圆形,然后根据当前的进度绘制一个红色的半圆形。可以使用 `setProgress()` 和 `setMax()` 方法来更新进度条的进度和最大值。在 `onMeasure()` 方法中,我们使用 `setMeasuredDimension()` 方法来设置视图的大小。
阅读全文