Androidで背景等の図形を書く場合、
Rectangle : 四角形
Oval : 楕円形
Line : 線
Ring : 円
はXMLで描画可能ですが、
三角形や星形などの複雑な図形はXMLでは難しいです。
なので、Viewクラスを拡張してプログラムで書いちゃいます。
Viewクラスの拡張
三角形を例に書いていきます。
public class Triangle extends View {
private int color = Color.RED;
public Triangle(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setColor(int color) {
this.color = color;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int height = getMeasuredHeight();
int width = getMeasuredWidth();
int centerHorizontal = width / 2;
int shapeWidth = width / 5;
// set color and style
Paint paint = new Paint();
paint.setColor(this.color);
paint.setStyle(Paint.Style.FILL);
paint.setAntiAlias(true);
// set shape
Path path = new Path();
path.moveTo(center - shapeWidth / 2, 0);
path.lineTo(center, height);
path.lineTo(center + shapeWidth / 2, 0);
path.lineTo(center - shapeWidth / 2, 0);
path.close();
// draw on canvas
canvas.drawPath(path, paint);
}
}
あとは、これをViewパーツとしてLayoutのXMLで設定すれば、三角形が表示されます。

0 件のコメント:
コメントを投稿