Android 自定义 View 实现指定颜色和圆角的椭圆
在 Android 中,可以通过自定义 View 类来实现画指定颜色和圆角大小的椭圆。下面是一个示例代码:
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
public class CustomOvalView extends View {
private Paint paint;
private int ovalColor;
private float cornerRadius;
public CustomOvalView(Context context) {
super(context);
init();
}
public CustomOvalView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CustomOvalView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
paint = new Paint();
ovalColor = Color.RED; // 默认颜色为红色
cornerRadius = 50; // 默认圆角半径为50
}
public void setOvalColor(int color) {
ovalColor = color;
invalidate(); // 重新绘制 View
}
public void setCornerRadius(float radius) {
cornerRadius = radius;
invalidate(); // 重新绘制 View
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 计算椭圆的位置和大小
float left = getPaddingLeft();
float top = getPaddingTop();
float right = getWidth() - getPaddingRight();
float bottom = getHeight() - getPaddingBottom();
RectF rectF = new RectF(left, top, right, bottom);
// 绘制椭圆
paint.setColor(ovalColor);
canvas.drawOval(rectF, paint);
}
}
在使用时,可以将 CustomOvalView 添加到布局文件中,然后通过调用 setOvalColor() 方法和 setCornerRadius() 方法来设置颜色和圆角大小。例如:
<com.example.CustomOvalView
android:id="@+id/ovalView"
android:layout_width="200dp"
android:layout_height="100dp"
android:padding="10dp" />
CustomOvalView ovalView = findViewById(R.id.ovalView);
ovalView.setOvalColor(Color.BLUE);
ovalView.setCornerRadius(20);
原文地址: https://www.cveoy.top/t/topic/qtcz 著作权归作者所有。请勿转载和采集!