android 实现半圆环效果
时间: 2023-10-25 14:07:45 浏览: 39
实现半圆环效果可以通过自定义 View 来实现。
下面是一个实现的示例代码:
```java
public class SemiCircleView extends View {
private Paint mPaint;
private RectF mRectF;
private int mStartAngle;
private int mSweepAngle;
private int mStrokeWidth;
private int mColor;
public SemiCircleView(Context context) {
this(context, null);
}
public SemiCircleView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SemiCircleView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.SemiCircleView);
mStartAngle = typedArray.getInt(R.styleable.SemiCircleView_startAngle, 0);
mSweepAngle = typedArray.getInt(R.styleable.SemiCircleView_sweepAngle, 180);
mStrokeWidth = typedArray.getDimensionPixelSize(R.styleable.SemiCircleView_strokeWidth, 10);
mColor = typedArray.getColor(R.styleable.SemiCircleView_color, Color.RED);
typedArray.recycle();
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(mStrokeWidth);
mPaint.setColor(mColor);
mRectF = new RectF();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int width = getWidth();
int height = getHeight();
mRectF.set(mStrokeWidth / 2, mStrokeWidth / 2, width - mStrokeWidth / 2, height - mStrokeWidth / 2);
canvas.drawArc(mRectF, mStartAngle, mSweepAngle, false, mPaint);
}
public void setStartAngle(int startAngle) {
mStartAngle = startAngle;
invalidate();
}
public void setSweepAngle(int sweepAngle) {
mSweepAngle = sweepAngle;
invalidate();
}
public void setStrokeWidth(int strokeWidth) {
mStrokeWidth = strokeWidth;
mPaint.setStrokeWidth(mStrokeWidth);
invalidate();
}
public void setColor(int color) {
mColor = color;
mPaint.setColor(mColor);
invalidate();
}
}
```
在布局文件中使用:
```xml
<com.example.widget.SemiCircleView
android:id="@+id/semiCircleView"
android:layout_width="200dp"
android:layout_height="100dp"
app:startAngle="0"
app:sweepAngle="180"
app:strokeWidth="20dp"
app:color="@color/colorAccent"/>
```
然后在代码中动态设置属性值即可实现半圆环效果。