Shape

Shape相关的包为:android.graphics.drawable.shapes, 下面是Shape的类图:

1.1、Shape
 

形状的基类,它是抽象类。

Shape的子类通过ShapeDrawable(Shape shape)创建了一个Drawable的子类的实例,Drawable可以用在设置背景或者前景等很多地方。

1.2、PathShape

任意形状。

使用示例(绘制一个二阶贝塞尔曲线):

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);
1.3、RectShape

直角矩形

使用示例:

RectShape rectShape = new RectShape();
ShapeDrawable shapeDrawable = new ShapeDrawable(rectShape);
shapeDrawable.getPaint().setColor(Color.RED);
1.4、RoundRectShape

圆角矩形

使用示例:

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);
1.5、ArcShape

扇形

使用示例:

ArcShape arcShape = new ArcShape(0, 90);
ShapeDrawable shapeDrawable = new ShapeDrawable(arcShape);
shapeDrawable.getPaint().setColor(Color.RED);
1.6、OvalShape

椭圆形

使用示例:

OvalShape ovalShape = new OvalShape();
ShapeDrawable shapeDrawable = new ShapeDrawable(ovalShape);
shapeDrawable.getPaint().setColor(Color.RED);
1.7、自定义Shape

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"));