android开发日常总结

[Android日常]绘制弧形渐变背景

2021-01-04  本文已影响0人  aitality

最近要修改用户空间头部信息显示,参考了好多APP的用户空间,都有一个弧形的背景,看着挺漂亮的。实现这种效果,有两种实现方式:1、作图;2、通过代码进行绘制。今天就讲讲如何通过canvas进行绘制。

一、用到的知识点

1、Android或或者Java中绘图需要用到CanvasPaint类,一个是画布,一个是画笔;
2、canvas.drawRectcanvas.drawArc的使用;
3、LinearGradient线性渐变和Paint.setShader的使用;

二、具体代码

public class ArcBackgroundView extends View {

    private Paint mPaint;
    private int mStartColor, mEndColor;

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

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

    public ArcBackgroundView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setStyle(Paint.Style.FILL);
        mStartColor = ContextCompat.getColor(context, R.color.top_gradient_start);
        mEndColor = ContextCompat.getColor(context, R.color.top_gradient_end);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int width = getWidth();
        int height = getHeight();

        LinearGradient linearGradient = new LinearGradient(0,0, width, height, mStartColor, mEndColor, Shader.TileMode.CLAMP);
        mPaint.setShader(linearGradient);
        canvas.drawRect(new Rect(0, 0 , width, height-20), mPaint);
        RectF oval = new RectF(0, height-40, width, height);
        canvas.drawArc(oval,0,180,false,mPaint);//画圆弧,这个时候,绘制没有经过圆心
    }

上一篇 下一篇

猜你喜欢

热点阅读