天天看點

自定義圓形背景RelativeLayout

最近公司項目愛用到圓角背景的RelativeLayout,一般圓角背景的實作思路無非就是兩種,第一種用.xml實作,需要用到.9圖檔,防止圖檔變形,如果要改變背景顔色的話,不可避免的要找美工妹子作圖,看着我的美工妹子一臉幽怨的小表情,我打算還是用第二種方法吧,就是自已用代碼繪制一個,要改變角度,要改變顔色,改下設定就可以了,輕松又便捷,簡單又友善,媽媽再也不用擔心我的明天了~~~~

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
import android.widget.RelativeLayout;

public class RoundRelativeLayoutTest extends RelativeLayout {
    private final RectF roundRect = new RectF();
    private float rect_adius = 10;  //機關為像素
    private final Paint maskPaint = new Paint();
    private final Paint zonePaint = new Paint();
    private View mView;
    private Context mContext;
    public RoundRelativeLayoutTest(Context context) {
        super(context);
        init();
    }

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

    public RoundRelativeLayoutTest(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }
    private void init() {
        maskPaint.setAntiAlias(true);
        maskPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        //        zonePaint.setAntiAlias(true);
        zonePaint.setColor(Color.WHITE);
    }
    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        int w = getWidth();
        int h = getHeight();
        roundRectSet(w, h);
    }
    @Override
    public void draw(Canvas canvas) {
        canvasSetLayer(canvas);
        super.draw(canvas);
        canvas.restore();
    }
    /**
     * 從新設定圓角     * @param adius
     */
    public void setRectAdius(float adius) {
        rect_adius = adius;
        if (mView != null) {
            mView.invalidate();
        }
    }

    /**
     * 圓角區域設定     * @param width     * @param height
     */
    public void roundRectSet(int width, int height) {
        roundRect.set(0, 0, width, height);
    }

    /**
     * 畫布區域裁剪     * @param canvas
     */
    public void canvasSetLayer(Canvas canvas) {
        canvas.saveLayer(roundRect, zonePaint, Canvas.ALL_SAVE_FLAG);
        canvas.drawRoundRect(roundRect, rect_adius, rect_adius, zonePaint);
        //
        canvas.saveLayer(roundRect, maskPaint, Canvas.ALL_SAVE_FLAG);
    }
}