设置倾斜的背景图

2018-09-04  本文已影响0人  _成长ing_

效果如图


倾斜的背景.PNG

在自定义布局中,我们在onDraw()方法里,通过Paint可以绘制各种各样的图形,通过Path的move(x,y),line(x,y)可以描绘各种各样的图片,如图所示的红色背景是非常简单的一种效果,从坐标(0,height/2) -> (width/2,0) -> (width,0) -> (0,height)即可,代码如下:

public class TriangleView extends View {

    private Paint mPaint;

    public TriangleView(Context context) {
        this(context, null);
    }

    public TriangleView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TriangleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setColor(Color.RED);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setStrokeWidth(5);
    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);

        Path iPath = new Path();
        iPath.moveTo(0, getHeight() / 2);
        iPath.lineTo(getWidth()/2, 0);
        iPath.lineTo(getWidth(), 0);
        iPath.lineTo(0, getHeight());
        iPath.close();
        canvas.drawPath(iPath, mPaint);
    }

    public void setBackGroundColor(int color) {
        mPaint.setColor(color);
        invalidate();
    }
}

上一篇 下一篇

猜你喜欢

热点阅读