Shape
相关的包为:android.graphics.drawable.shapes
, 下面是Shape
的类图:
形状的基类,它是抽象类。
Shape
的子类通过ShapeDrawable(Shape shape)
创建了一个Drawable
的子类的实例,Drawable
可以用在设置背景或者前景等很多地方。
任意形状。
使用示例(绘制一个二阶贝塞尔曲线):
Point startPoint = new Point(0, 0);
Point endPoint = new Point(0, 600);
Point controlPoint = new Point(600, 600);
Paint paint = new Paint();
// 抗锯齿
paint.setAntiAlias(true);
// 防抖动
paint.setDither(true);
paint.setColor(Color.BLACK);
// 笔宽
paint.setStrokeWidth(5);
// 空心
paint.setStyle(Paint.Style.STROKE);
Path path = new Path();
// 重置路径
path.reset();
// 起点
path.moveTo(startPoint.x, startPoint.y);
// 控制点和终点
path.quadTo(controlPoint.x, controlPoint.y, endPoint.x, endPoint.y);
PathShape pathShape = new PathShape(path, 100, 100);
ShapeDrawable shapeDrawable = new ShapeDrawable(pathShape);
直角矩形
使用示例:
RectShape rectShape = new RectShape();
ShapeDrawable shapeDrawable = new ShapeDrawable(rectShape);
shapeDrawable.getPaint().setColor(Color.RED);
圆角矩形
使用示例:
float[] r = {10, 10 ,10 ,10 ,10, 10 ,10, 10};
RoundRectShape rectShape = new RoundRectShape(r, null, null);
ShapeDrawable shapeDrawable = new ShapeDrawable(rectShape);
shapeDrawable.getPaint().setColor(Color.RED);
扇形
使用示例:
ArcShape arcShape = new ArcShape(0, 90);
ShapeDrawable shapeDrawable = new ShapeDrawable(arcShape);
shapeDrawable.getPaint().setColor(Color.RED);
椭圆形
使用示例:
OvalShape ovalShape = new OvalShape();
ShapeDrawable shapeDrawable = new ShapeDrawable(ovalShape);
shapeDrawable.getPaint().setColor(Color.RED);
Android SDK Framework API
只提供了最基本的5种常见形状。 如果想实现其他更复杂的形状,就需要自己实现,这就是自定义Shape
。
自定义Shape
就是自己写一个类,继承自Shape
这个抽象类,然后, 重写public void draw(Canvas canvas, Paint paint)
方法,与自定义View
的本质一样,都是在Canvas
上用Paint
绘图。
示例:
public class ForegroundShape extends Shape {
@Override
public void draw(Canvas canvas, Paint paint) {
float width = getWidth();
float heigth = getHeight();
canvas.drawLine(0, 0, width, 0, paint);
canvas.drawLine(0, heigth, width, heigth, paint);
}
}
使用示例:
ForegroundShape shape = new ForegroundShape();
ShapeDrawable shapeDrawable = new ShapeDrawable(shape);
shapeDrawable.getPaint().setColor(Color.parseColor("#70333333"));