自定義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);
}
}