我想在android studio中画一个圆圈,半圆和三角形。有没有简单的方法在android studio中绘制形状,或者我应该为每个形状使用图像?
我试过这个作为可绘制的来源
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >
<solid android:color="#000000"/>
但它不足以创建圆形和其他形状的精确外形。还有其他办法吗?
答案 0 :(得分:1)
您可以使用以下类来绘制半圆
public class MyView extends View {
public MyView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
float width = (float) getWidth();
float height = (float) getHeight();
float radius;
if (width > height) {
radius = height / 4;
} else {
radius = width / 4;
}
Path path = new Path();
path.addCircle(width / 2,
height / 2, radius,
Path.Direction.CW);
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setStrokeWidth(5);
paint.setStyle(Paint.Style.FILL);
float center_x, center_y;
final RectF oval = new RectF();
paint.setStyle(Paint.Style.STROKE);
center_x = width / 2;
center_y = height / 2;
oval.set(center_x - radius,
center_y - radius,
center_x + radius,
center_y + radius);
canvas.drawArc(oval, 90, 180, false, paint);
}
}
输出
答案 1 :(得分:1)
有两种选择;
1.通过代码
您需要定义自己的drawable(而不是View,因为View对于此任务来说很重要,为了获得最佳性能定义Drawable的继承者),然后在方法onDraw中绘制您的数字。例如:
public class MyDrawable extends Drawable {
@Override
public void onDraw(Canvas canvas) {
//call method from canvas to draw your figures or whatever,
//provide them by your custom paint (but please don't create them here)
}
}
<强> 2。通过XML
当支持库23.2问世时,所有开发人员都收到了api级别> 9的所有应用程序都可以使用的矢量drawable。所以你可以做下一步。
将补丁添加到xml中的组标记。你会有类似的东西:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:height="64dp"
android:width="64dp"
android:viewportHeight="600"
android:viewportWidth="600" >
<group>
<path android:pathData="some path data" />
<path android:pathData="some path data" />
<path android:pathData="some path data" />
</group>
</vector>
这就是全部。