Android Canvas绘制七巧板

心血来潮,封装了一个绘制彩色多边形的方法,并用这个方法绘制了一个七巧板(感觉绘制华容道太简单了)


代码如下:

public class CanvasPuzzle extends View {

    public CanvasPuzzle(Context context) {
        super(context);
    }

    public CanvasPuzzle(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CanvasPuzzle(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public CanvasPuzzle(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        Paint p = new Paint();
        p.setAntiAlias(true);

        drawPath(canvas,p,Color.RED, new float[][]{{0,0},{512,0},{256,256}});
        drawPath(canvas,p,Color.YELLOW, new float[][]{{0,0},{256,256},{0,512}});
        drawPath(canvas,p,Color.GREEN, new float[][]{{512,0},{512,256},{384,384},{384,128}});
        drawPath(canvas,p,Color.BLUE, new float[][]{{256,256},{384,128},{384,384}});
        drawPath(canvas,p,Color.BLACK, new float[][]{{128,384},{256,512},{0,512}});
        drawPath(canvas,p,Color.GRAY, new float[][]{{256,256},{384,384},{256,512},{128,384}});
        drawPath(canvas,p,Color.CYAN, new float[][]{{256,512},{512,256},{512,512}});
    }

    /**
     * 绘制彩色多边形
     * @param canvas Canvas画布
     * @param paint Paint画笔
     * @param color 颜色
     * @param points 二维数组表示多边形的顶点
     */
    private void drawPath(Canvas canvas, Paint paint, @ColorInt int color, float[][] points){
        if (paint == null){
            paint = new Paint();
        }else{
            paint.reset();
        }
        Path path = new Path();
        if (points.length < 3){
            return;
        }
        for (int i=0;i<points.length;i++){
            if (i==0){
                path.moveTo(points[i][0],points[i][1]);
            }else{
                path.lineTo(points[i][0],points[i][1]);
            }
        }
        path.close();
        paint.setColor(color);
        canvas.drawPath(path,paint);
    }

}



效果如下

Android Canvas绘制七巧板_第1张图片

你可能感兴趣的:(android,canvas)