天天看点

自定义圆形背景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);
    }
}