android實現一個弧形的背景

語言: CN / TW / HK

在專案的開發中,有時我們需要一個帶有弧形的介面來作為背景裝飾。

圖片1.png

設計這個view的方式比較簡單就是自定義繪製的方式,重新寫onDraw函式。

``` public class ArcView extends View { private int mWidth; private int mHeight;

private int mArcHeight; //圓弧的高度
private int mBgColor;   //背景顏色
private int lgColor;    //變化的最終顏色
private Paint mPaint;  //畫筆
private LinearGradient linearGradient;
private Rect rect=new Rect(0,0,0,0);//普通的矩形
private Path path=new Path();//用來繪製曲面

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

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

public ArcView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);

    TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ArcView);
    mArcHeight = typedArray.getDimensionPixelSize(R.styleable.ArcView_arcHeight, 0);
    mBgColor=typedArray.getColor(R.styleable.ArcView_bgColor, Color.parseColor("#303F9F"));
    lgColor = typedArray.getColor(R.styleable.ArcView_lgColor, mBgColor);
    mPaint = new Paint();
    mPaint.setAntiAlias(true);
    typedArray.recycle();
}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);

// Log.d("----","onSizeChanged"); linearGradient = new LinearGradient(0,0,getMeasuredWidth(),0, mBgColor,lgColor, Shader.TileMode.CLAMP ); mPaint.setShader(linearGradient); }

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    //設定成填充
    mPaint.setStyle(Paint.Style.FILL);
    mPaint.setColor(mBgColor);

    //繪製矩形
    rect.set(0, 0, mWidth, mHeight - mArcHeight);
    canvas.drawRect(rect, mPaint);

    //繪製路徑
    path.moveTo(0, mHeight - mArcHeight);
    path.quadTo(mWidth >> 1, mHeight, mWidth, mHeight - mArcHeight);
    canvas.drawPath(path, mPaint);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);
    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);

    if (widthMode == MeasureSpec.EXACTLY) {
        mWidth = widthSize;
    }
    if (heightMode == MeasureSpec.EXACTLY) {
        mHeight = heightSize;
    }
    setMeasuredDimension(mWidth, mHeight);
}

}

``` 宣告的屬性

```js

<declare-styleable name="ArcView">
    <attr name="arcHeight" format="dimension"/>
    <attr name="lgColor"   format="color"/>
    <attr name="bgColor" format="color"/>
</declare-styleable>

``` 程式碼比較簡單主要就是使用path繪製路徑,增加一個漸變的效果。