自定義ViewGroup形狀

自定義ViewGroup形狀

  • 重寫(xiě)ViewGroup的 dispatchDraw方法
  • 利用 Paint 的setXfermode方法,根據(jù)path的形狀繪制出不同形狀圖案的效果
  • 只替換各種形狀的path就可繪制出各種形狀

說(shuō)明:參考了一些網(wǎng)上的各種實(shí)現(xiàn)方式,這個(gè)是比較好的實(shí)現(xiàn)方式

device-2017-08-20-131344.png

github 地址
xml

 <com.example.ck.shapelayout.RadiusRelativelayout
        android:layout_width="250dp"
        android:layout_height="250dp"
        android:layout_centerInParent="true"
        app:corner_radius="50dp">

        <ImageView
            android:layout_width="250dp"
            android:layout_height="250dp"
            android:background="#f00"
            android:scaleType="fitXY"
            android:src="@mipmap/ic_launcher" />

    </com.example.ck.shapelayout.RadiusRelativelayout>
public class RadiusRelativelayout extends RelativeLayout {

    private float cornerRadius;
    private Path path;

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

    public RadiusRelativelayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RadiusRelativelayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RadiusRelativelayout);
        ;
        try {
            cornerRadius = typedArray.getDimension(R.styleable.RadiusRelativelayout_corner_radius, 0);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            typedArray.recycle();
        }
    }

    public RadiusRelativelayout setPath(Path path) {
        this.path = path;
        invalidate();
        return this;
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        //無(wú)設(shè)置空
        if (path == null && cornerRadius == 0) {
            super.dispatchDraw(canvas);
            return;
        }

        /**
         * @path 要顯示的形狀
         * 未設(shè)置path 設(shè)置了園角度
         */
        if (path == null) {
            path = new Path();
            path.addRoundRect(new RectF(0, 0, getMeasuredWidth(), getMeasuredHeight()), cornerRadius, cornerRadius, Path.Direction.CCW);
        }

        /**
         * 抗鋸齒
         */
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
       //保存圖層
        int save = canvas.saveLayer(0, 0, getWidth(), getHeight(), null, Canvas.ALL_SAVE_FLAG);

        super.dispatchDraw(canvas);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
        canvas.drawPath(path, paint);
        canvas.restoreToCount(save);
        paint.setXfermode(null);
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容