Android之布局转圆角

Android之布局转圆角


文章目录


说明

很多需求比较无语,需要某个布局转圆角,像个显眼包一样,所以为了满足显眼包,必须整呐

提示:以下是本篇文章正文内容,下面案例可供参考

一、效果图

说明:轮播图可以直接转圆角,图片也可以,我这里只是在轮播图外层嵌套了一个RoundRelativeLayout,直接对RoundRelativeLayout进行转角。

二、实现步骤

1.自定义RoundRelativeLayout

代码如下(示例):

java 复制代码
public class RoundRelativeLayout extends RelativeLayout {
    private final RectF roundRect = new RectF();
    private final Paint maskPaint = new Paint();
    private final Paint zonePaint = new Paint();
    private Context mContext;
    private float rect_adius = 20;  //圆角大小


    public RoundRelativeLayout(Context context) {
        super(context);
        init(context);
    }

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

    public RoundRelativeLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }


    private void init(Context context) {
        this.mContext = context;
        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;
        invalidate();
    }

    /**
     * 圆角区域设置
     *
     * @param width
     * @param height
     */
    private void roundRectSet(int width, int height) {
        roundRect.set(0, 0, width, height);
    }

    /**
     * 画布区域裁剪
     *
     * @param canvas
     */
    private 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);
    }
}

2.使用

说明:其实xml布局引用自定义这个就已经成功转角了,这里贴一下设置布局背景的代码,跟正常设置背景一样。

java 复制代码
relative_back.setBackgroundColor(Color.parseColor("#ffffff"))

总结

其实就是自定义RoundRelativeLayout进行转角,角度可设置,很简单。