Androidstudio的该类中public class DrawView extends View 如何画一个五角星
要在DrawView类中画一个五角星,你可以在onDraw方法中使用Path类来绘制。
以下是一个在DrawView类中绘制五角星的示例代码:
public class DrawView extends View {
private Paint mPaint;
public DrawView(Context context) {
super(context);
init();
}
public DrawView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public DrawView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mPaint = new Paint();
mPaint.setColor(Color.BLACK);
mPaint.setStyle(Paint.Style.FILL);
mPaint.setAntiAlias(true);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int width = getWidth();
int height = getHeight();
// 计算五角星的坐标
int cx = width / 2;
int cy = height / 2;
int radius = Math.min(width, height) / 2;
Path path = new Path();
// 计算五角星的五个顶点的坐标
float[] points = calculateStarPoints(cx, cy, radius, 5, 0);
// 绘制五角星
path.moveTo(points[0], points[1]);
for (int i = 2; i < points.length; i += 2) {
path.lineTo(points[i], points[i + 1]);
}
path.close();
canvas.drawPath(path, mPaint);
}
// 计算五角星的顶点坐标
private float[] calculateStarPoints(float cx, float cy, float radius, int numPoints, float startAngle) {
float angle = (float) (Math.PI * 2 / numPoints);
float rotation = (float) (Math.PI / 2 + startAngle);
float[] points = new float[numPoints * 2];
for (int i = 0; i < numPoints * 2; i += 2) {
points[i] = cx + (float) (radius * Math.cos(rotation));
points[i + 1] = cy + (float) (radius * Math.sin(rotation));
rotation += angle;
}
return points;
}
}
在这个示例中,我们在onDraw方法中使用Path类来绘制五角星。首先,我们计算五角星的中心点坐标和半径,然后使用calculateStarPoints方法计算五角星的顶点坐标。接着,我们使用path.moveTo方法移动到第一个顶点,然后使用path.lineTo方法连接其他顶点,最后使用path.close方法关闭路径。最后,我们使用Canvas的drawPath方法将路径绘制到屏幕上。
要在布局文件中使用这个自定义的View,你可以添加如下代码:
<com.example.yourpackage.DrawView
android:layout_width="match_parent"
android:layout_height="match_parent" />
确保将com.example.yourpackage替换为你自己的包名
原文地址: http://www.cveoy.top/t/topic/iTXr 著作权归作者所有。请勿转载和采集!