Android Xfermode 實戰 實現圓形、圓角圖片
轉載請標明出處:http://blog.csdn.net/lmj623565791/article/details/42094215,本文出自:【張鴻洋的博客】
1、概述
其實這篇本來準備Android BitmapShader 實戰 實現圓形、圓角圖片放到一篇里面,結果由于篇幅原因就獨立出來了~在很久以前也寫過一個利用Xfermode 實現圓形、圓角圖片的,但是那個繼承的是View,其實繼承ImageView能方便點,最起碼省去了onMeasure里面自己去策略,以及不需要自己去提供設置圖片的方法,最主要的是大家對ImageView的API會比較熟悉,用起來會比較順手。
好了,本篇就當是個記錄了~~~電腦上代碼放幾天就找不到了,還是放博客里面,有需要自己過來看看~~~
2、原理
原理就不多說了,這張圖在我博客里出現的次數大概有3次以上了,我們這次使用的模式DST_IN;也就是先繪制圖片,再繪制形狀了~~
3、Xfermode實戰
1、自定義屬性
首先依然是自定義屬性,和上篇一致。
<?xml version="1.0" encoding="utf-8"?> <resources> <attr name="borderRadius" format="dimension" /> <attr name="type"> <enum name="circle" value="0" /> <enum name="round" value="1" /> </attr> <declare-styleable name="RoundImageViewByXfermode"> <attr name="borderRadius" /> <attr name="type" /> </declare-styleable> </resources>
2、構造中獲取屬性
public class RoundImageViewByXfermode extends ImageView { private Paint mPaint; private Xfermode mXfermode = new PorterDuffXfermode(Mode.DST_IN); private Bitmap mMaskBitmap; private WeakReference<Bitmap> mWeakBitmap; /** * 圖片的類型,圓形or圓角 */ private int type; public static final int TYPE_CIRCLE = 0; public static final int TYPE_ROUND = 1; /** * 圓角大小的默認值 */ private static final int BODER_RADIUS_DEFAULT = 10; /** * 圓角的大小 */ private int mBorderRadius; public RoundImageViewByXfermode(Context context) { this(context,null); mPaint = new Paint(); mPaint.setAntiAlias(true); } public RoundImageViewByXfermode(Context context, AttributeSet attrs) { super(context, attrs); mPaint = new Paint(); mPaint.setAntiAlias(true); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RoundImageViewByXfermode); mBorderRadius = a.getDimensionPixelSize( R.styleable.RoundImageViewByXfermode_borderRadius, (int) TypedValue .applyDimension(TypedValue.COMPLEX_UNIT_DIP, BODER_RADIUS_DEFAULT, getResources() .getDisplayMetrics()));// 默認為10dp Log.e("TAG", mBorderRadius+""); type = a.getInt(R.styleable.RoundImageViewByXfermode_type, TYPE_CIRCLE);// 默認為Circle a.recycle(); }
獲取自定義屬性,然后還寫些成員變量~~
3、onMeasure
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); /** * 如果類型是圓形,則強制改變view的寬高一致,以小值為準 */ if (type == TYPE_CIRCLE) { int width = Math.min(getMeasuredWidth(), getMeasuredHeight()); setMeasuredDimension(width, width); } }
在onMeasure中,如果是圓形則重新設置view大小。
4、onDraw
@SuppressLint("DrawAllocation") @Override protected void onDraw(Canvas canvas) { //在緩存中取出bitmap Bitmap bitmap = mWeakBitmap == null ? null : mWeakBitmap.get(); if (null == bitmap || bitmap.isRecycled()) { //拿到Drawable Drawable drawable = getDrawable(); //獲取drawable的寬和高 int dWidth = drawable.getIntrinsicWidth(); int dHeight = drawable.getIntrinsicHeight(); if (drawable != null) { //創建bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Config.ARGB_8888); float scale = 1.0f; //創建畫布 Canvas drawCanvas = new Canvas(bitmap); //按照bitmap的寬高,以及view的寬高,計算縮放比例;因為設置的src寬高比例可能和imageview的寬高比例不同,這里我們不希望圖片失真; if (type == TYPE_ROUND) { // 如果圖片的寬或者高與view的寬高不匹配,計算出需要縮放的比例;縮放后的圖片的寬高,一定要大于我們view的寬高;所以我們這里取大值; scale = Math.max(getWidth() * 1.0f / dWidth, getHeight() * 1.0f / dHeight); } else { scale = getWidth() * 1.0F / Math.min(dWidth, dHeight); } //根據縮放比例,設置bounds,相當于縮放圖片了 drawable.setBounds(0, 0, (int) (scale * dWidth), (int) (scale * dHeight)); drawable.draw(drawCanvas); if (mMaskBitmap == null || mMaskBitmap.isRecycled()) { mMaskBitmap = getBitmap(); } // Draw Bitmap. mPaint.reset(); mPaint.setFilterBitmap(false); mPaint.setXfermode(mXfermode); //繪制形狀 drawCanvas.drawBitmap(mMaskBitmap, 0, 0, mPaint); mPaint.setXfermode(null); //將準備好的bitmap繪制出來 canvas.drawBitmap(bitmap, 0, 0, null); //bitmap緩存起來,避免每次調用onDraw,分配內存 mWeakBitmap = new WeakReference<Bitmap>(bitmap); } } //如果bitmap還存在,則直接繪制即可 if (bitmap != null) { mPaint.setXfermode(null); canvas.drawBitmap(bitmap, 0.0f, 0.0f, mPaint); return; } } /** * 繪制形狀 * @return */ public Bitmap getBitmap() { Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setColor(Color.BLACK); if (type == TYPE_ROUND) { canvas.drawRoundRect(new RectF(0, 0, getWidth(), getHeight()), mBorderRadius, mBorderRadius, paint); } else { canvas.drawCircle(getWidth() / 2, getWidth() / 2, getWidth() / 2, paint); } return bitmap; }
在onDraw中拿到drawable,然后獲取drawable的寬和高,根據當前的type和view的寬和高,進行適當的縮放。具體原理:參考上篇的matrix的scale計算,原理一致。
然后就是設置Xfermode,getBitmap會根據type返回圖形,直接繪制到內存中的bitmap上即可。最后把bitmap緩存起來,避免每次onDraw都分配內存和重啟繪圖。
大家可以進行擴展type,繪制心形、三角形什么的,直接在getBitmap里面添加分支就可以。
最后記得invalidate中做一些處理:
@Override public void invalidate() { mWeakBitmap = null; if (mMaskBitmap != null) { mMaskBitmap.recycle(); mMaskBitmap = null; } super.invalidate(); }
主要是因為我們緩存了,當調用invalidate時,將緩存清除。
4、布局文件及效果圖
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:zhy="http://schemas.android.com/apk/res/com.zhy.variousshapeimageview" android:layout_width="match_parent" android:layout_height="wrap_content" > <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <com.zhy.view.RoundImageViewByXfermode android:layout_width="130dp" android:layout_height="130dp" android:layout_margin="10dp" android:src="@drawable/qiqiu" > </com.zhy.view.RoundImageViewByXfermode> <com.zhy.view.RoundImageViewByXfermode android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="10dp" android:src="@drawable/aa" zhy:borderRadius="30dp" zhy:type="round" > </com.zhy.view.RoundImageViewByXfermode> <com.zhy.view.RoundImageViewByXfermode android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="10dp" android:src="@drawable/aa" zhy:type="circle" > </com.zhy.view.RoundImageViewByXfermode> <com.zhy.view.RoundImageViewByXfermode android:layout_width="40dp" android:layout_height="40dp" android:layout_margin="10dp" android:src="@drawable/aa" zhy:type="circle" > </com.zhy.view.RoundImageViewByXfermode> </LinearLayout> </ScrollView>
效果圖:
好了,比較簡單~~
聲明下:本例參考了:https://github.com/MostafaGazar/CustomShapeImageView ;不過對其中的部分代碼進行了改變,比如CustomShapeImageView如果圖片為長方形,但是設置為circle類型,效果依然是矩形;以及會對bitmap比例和view比例不一致的直接進行壓縮,類似fitxy的效果~~~主要對這兩點進行了修改~~當然了,該案例比本博客功能要強大,看名字也知道,支持很多形狀,以及支持SVG~大家自行進行參考~
我新建了一個QQ群,方便大家交流。群號:423372824
----------------------------------------------------------------------------------------------------------
博主部分視頻已經上線,如果你不喜歡枯燥的文本,請猛戳(初錄,期待您的支持):
2、Android自定義控件實戰 打造Android流式布局和熱門標簽
來自: http://blog.csdn.net//lmj623565791/article/details/42094215