Android studio如何画自己想要的图形
时间: 2024-04-20 08:23:38 浏览: 22
在Android Studio中,你可以使用Canvas和Paint类来绘制自定义图形。下面是一个简单的示例,演示如何在自定义View中绘制一个圆形:
1. 创建一个自定义的View类,继承自View:
```java
public class MyCustomView extends View {
private Paint mPaint;
public MyCustomView(Context context) {
super(context);
init();
}
public MyCustomView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
mPaint = new Paint();
mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.FILL);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int centerX = getWidth() / 2;
int centerY = getHeight() / 2;
int radius = Math.min(centerX, centerY);
canvas.drawCircle(centerX, centerY, radius, mPaint);
}
}
```
2. 在你的布局文件中添加自定义的View:
```xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.yourpackage.MyCustomView
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
```
记得将`com.example.yourpackage.MyCustomView`替换为你自定义View的完整包名和类名。
以上示例演示了如何在自定义View中绘制一个红色的圆形。你可以通过修改`onDraw`方法来实现绘制其他形状、颜色和样式的图形。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)