Android中使用BitmapShader類來制作各種圖片的圓角
public BitmapShader(Bitmap bitmap,Shader.TileMode tileX,Shader.TileMode tileY)
調(diào)用這個類來產(chǎn)生一個畫有一個位圖的渲染器(Shader)。
bitmap:在渲染器內(nèi)使用的位圖
(1)tileX:The tiling mode for x to draw the bitmap in. 在位圖上X方向花磚模式
(2)tileY:The tiling mode for y to draw the bitmap in. 在位圖上Y方向花磚模式
TileMode:(一共有三種)
(1)CLAMP:如果渲染器超出原始邊界范圍,會復(fù)制范圍內(nèi)邊緣染色。
(2)REPEAT:橫向和縱向的重復(fù)渲染器圖片,平鋪。
(3)MIRROR:橫向和縱向的重復(fù)渲染器圖片,這個和REPEAT 重復(fù)方式不一樣,他是以鏡像方式平鋪。
還是不太明白?那看一下效果圖吧!
對于我們的圓角,以及圓形,我們設(shè)置的模式都是CLAMP ,但是你會不會會有一個疑問:
view的寬或者高大于我們的bitmap寬或者高豈不是會拉伸?
嗯,我們會為BitmapShader設(shè)置一個matrix,去適當(dāng)?shù)姆糯蠡蛘呖s小圖片,不會讓“ view的寬或者高大于我們的bitmap寬或者高 ”此條件成立的。
到此我們的原理基本介紹完畢了,拿到drawable轉(zhuǎn)化為bitmap,然后直接初始化BitmapShader,畫筆設(shè)置Shader,最后在onDraw里面進(jìn)行畫圓就行了。
基本用法及實(shí)例
首先就來看看利用BitmapShader實(shí)現(xiàn)的圓形或者圓角。
我們這里直接繼承ImageView,這樣大家設(shè)置圖片的代碼會比較熟悉;但是我們需要支持兩種模式,那么就需要自定義屬性了:
1、自定義屬性
values/attr.xml
<?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="RoundImageView"> <attr name="borderRadius" /> <attr name="type" /> </declare-styleable> </resources>
我們定義了一個枚舉和一個圓角的大小borderRadius。
2、獲取自定義屬性
public class RoundImageView extends ImageView { /** * 圖片的類型,圓形or圓角 */ private int type; private static final int TYPE_CIRCLE = 0; private static final int TYPE_ROUND = 1; /** * 圓角大小的默認(rèn)值 */ private static final int BODER_RADIUS_DEFAULT = 10; /** * 圓角的大小 */ private int mBorderRadius; /** * 繪圖的Paint */ private Paint mBitmapPaint; /** * 圓角的半徑 */ private int mRadius; /** * 3x3 矩陣,主要用于縮小放大 */ private Matrix mMatrix; /** * 渲染圖像,使用圖像為繪制圖形著色 */ private BitmapShader mBitmapShader; /** * view的寬度 */ private int mWidth; private RectF mRoundRect; public RoundImageView(Context context, AttributeSet attrs) { super(context, attrs); mMatrix = new Matrix(); mBitmapPaint = new Paint(); mBitmapPaint.setAntiAlias(true); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RoundImageView); mBorderRadius = a.getDimensionPixelSize( R.styleable.RoundImageView_borderRadius, (int) TypedValue .applyDimension(TypedValue.COMPLEX_UNIT_DIP, BODER_RADIUS_DEFAULT, getResources() .getDisplayMetrics()));// 默認(rèn)為10dp type = a.getInt(R.styleable.RoundImageView_type, TYPE_CIRCLE);// 默認(rèn)為Circle a.recycle(); }
可以看到我們的一些成員變量,基本都加了注釋;然后在構(gòu)造方法中獲取了我們的自定義屬性,以及部分變量的初始化。
3、onMeasure
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { Log.e("TAG", "onMeasure"); super.onMeasure(widthMeasureSpec, heightMeasureSpec); /** * 如果類型是圓形,則強(qiáng)制改變view的寬高一致,以小值為準(zhǔn) */ if (type == TYPE_CIRCLE) { mWidth = Math.min(getMeasuredWidth(), getMeasuredHeight()); mRadius = mWidth / 2; setMeasuredDimension(mWidth, mWidth); } }
我們復(fù)寫了onMeasure方法,主要用于當(dāng)設(shè)置類型為圓形時,我們強(qiáng)制讓view的寬和高一致。
接下來只剩下設(shè)置BitmapShader和繪制了
4、設(shè)置BitmapShader
/** * 初始化BitmapShader */ private void setUpShader() { Drawable drawable = getDrawable(); if (drawable == null) { return; } Bitmap bmp = drawableToBitamp(drawable); // 將bmp作為著色器,就是在指定區(qū)域內(nèi)繪制bmp mBitmapShader = new BitmapShader(bmp, TileMode.CLAMP, TileMode.CLAMP); float scale = 1.0f; if (type == TYPE_CIRCLE) { // 拿到bitmap寬或高的小值 int bSize = Math.min(bmp.getWidth(), bmp.getHeight()); scale = mWidth * 1.0f / bSize; } else if (type == TYPE_ROUND) { // 如果圖片的寬或者高與view的寬高不匹配,計算出需要縮放的比例;縮放后的圖片的寬高,一定要大于我們view的寬高;所以我們這里取大值; scale = Math.max(getWidth() * 1.0f / bmp.getWidth(), getHeight() * 1.0f / bmp.getHeight()); } // shader的變換矩陣,我們這里主要用于放大或者縮小 mMatrix.setScale(scale, scale); // 設(shè)置變換矩陣 mBitmapShader.setLocalMatrix(mMatrix); // 設(shè)置shader mBitmapPaint.setShader(mBitmapShader); }
在setUpShader中,首先對drawable轉(zhuǎn)化為我們的bitmap;
然后初始化
mBitmapShader = new BitmapShader(bmp, TileMode.CLAMP, TileMode.CLAMP);
接下來,根據(jù)類型以及bitmap和view的寬高,計算scale;
關(guān)于scale的計算:
(1)圓形時:取bitmap的寬或者高的小值作為基準(zhǔn),如果采用大值,縮放后肯定不能填滿我們的圓形區(qū)域。然后,view的mWidth/bSize ; 得到的就是scale。
(2)圓角時:因?yàn)樵O(shè)計到寬/高比例,我們分別getWidth() * 1.0f / bmp.getWidth() 和 getHeight() * 1.0f / bmp.getHeight() ;最終取大值,因?yàn)槲覀円屪罱K縮放完成的圖片一定要大于我們的view的區(qū)域,有點(diǎn)類似centerCrop;
(3)比如:view的寬高為10*20;圖片的寬高為5*100 ; 最終我們應(yīng)該按照寬的比例放大,而不是按照高的比例縮??;因?yàn)槲覀冃枰尶s放后的圖片,自定大于我們的view寬高,并保證原圖比例。
有了scale,就可以設(shè)置給我們的matrix;
然后使用mBitmapShader.setLocalMatrix(mMatrix);
最后將bitmapShader設(shè)置給paint。
關(guān)于drawable轉(zhuǎn)bitmap的代碼:
/** * drawable轉(zhuǎn)bitmap * * @param drawable * @return */ private Bitmap drawableToBitamp(Drawable drawable) { if (drawable instanceof BitmapDrawable) { BitmapDrawable bd = (BitmapDrawable) drawable; return bd.getBitmap(); } int w = drawable.getIntrinsicWidth(); int h = drawable.getIntrinsicHeight(); Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, w, h); drawable.draw(canvas); return bitmap; }
最后我們會在onDraw里面調(diào)用setUpShader(),然后進(jìn)行繪制。
5、繪制
到此,就剩下最后一步繪制了,因?yàn)槲覀兊姆秶?,以及縮放都完成了,所以真的只剩下繪制了。
@Override protected void onDraw(Canvas canvas) { if (getDrawable() == null) { return; } setUpShader(); if (type == TYPE_ROUND) { canvas.drawRoundRect(mRoundRect, mBorderRadius, mBorderRadius, mBitmapPaint); } else { canvas.drawCircle(mRadius, mRadius, mRadius, mBitmapPaint); // drawSomeThing(canvas); } } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); // 圓角圖片的范圍 if (type == TYPE_ROUND) mRoundRect = new RectF(0, 0, getWidth(), getHeight()); }
繪制就很簡單了,畫個圓,圓角矩形什么的。圓角矩形的限定范圍mRoundRect在onSizeChanged里面進(jìn)行了初始化。
6、狀態(tài)的存儲與恢復(fù)
當(dāng)然了,如果內(nèi)存不足,而恰好我們的Activity置于后臺,不幸被重啟,或者用戶旋轉(zhuǎn)屏幕造成Activity重啟,我們的View應(yīng)該也能盡可能的去保存自己的屬性。
狀態(tài)保存什么用處呢?比如,現(xiàn)在一個的圓角大小是10dp,用戶點(diǎn)擊后變成50dp;當(dāng)用戶旋轉(zhuǎn)以后,或者長時間置于后臺以后,返回我們的Activity應(yīng)該還是50dp;
我們簡單的存儲一下,當(dāng)前的type以及mBorderRadius
private static final String STATE_INSTANCE = "state_instance"; private static final String STATE_TYPE = "state_type"; private static final String STATE_BORDER_RADIUS = "state_border_radius"; @Override protected Parcelable onSaveInstanceState() { Bundle bundle = new Bundle(); bundle.putParcelable(STATE_INSTANCE, super.onSaveInstanceState()); bundle.putInt(STATE_TYPE, type); bundle.putInt(STATE_BORDER_RADIUS, mBorderRadius); return bundle; } @Override protected void onRestoreInstanceState(Parcelable state) { if (state instanceof Bundle) { Bundle bundle = (Bundle) state; super.onRestoreInstanceState(((Bundle) state) .getParcelable(STATE_INSTANCE)); this.type = bundle.getInt(STATE_TYPE); this.mBorderRadius = bundle.getInt(STATE_BORDER_RADIUS); } else { super.onRestoreInstanceState(state); } }
代碼比較簡單。我們文章中的demo中,第一個,第四個是可以點(diǎn)擊的,點(diǎn)擊后會發(fā)生變化,你可以點(diǎn)擊后,然后旋轉(zhuǎn)屏幕進(jìn)行測試。
同時我們也對外公布了兩個方法,用于動態(tài)修改圓角大小和type
public void setBorderRadius(int borderRadius) { int pxVal = dp2px(borderRadius); if (this.mBorderRadius != pxVal) { this.mBorderRadius = pxVal; invalidate(); } } public void setType(int type) { if (this.type != type) { this.type = type; if (this.type != TYPE_ROUND && this.type != TYPE_CIRCLE) { this.type = TYPE_CIRCLE; } requestLayout(); } } public int dp2px(int dpVal) { return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpVal, getResources().getDisplayMetrics()); }
最后貼一下我們的布局文件和MainActivity。
6、調(diào)用
布局文件:
<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.RoundImageView android:id="@+id/id_qiqiu" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="10dp" android:src="@drawable/qiqiu" > </com.zhy.view.RoundImageView> <com.zhy.view.RoundImageView android:layout_width="200dp" android:layout_height="200dp" android:layout_margin="10dp" android:src="@drawable/aa" > </com.zhy.view.RoundImageView> <com.zhy.view.RoundImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="10dp" android:src="@drawable/icon" > </com.zhy.view.RoundImageView> <com.zhy.view.RoundImageView android:id="@+id/id_meinv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="10dp" android:src="@drawable/aa" zhy:borderRadius="20dp" zhy:type="round" > </com.zhy.view.RoundImageView> <com.zhy.view.RoundImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="10dp" android:src="@drawable/icon" zhy:borderRadius="40dp" zhy:type="round" > </com.zhy.view.RoundImageView> <com.zhy.view.RoundImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="10dp" android:src="@drawable/qiqiu" zhy:borderRadius="60dp" zhy:type="round" > </com.zhy.view.RoundImageView> </LinearLayout> </ScrollView>
沒撒,ScrollView里面一個線性布局,里面一堆RoundImageView。
MainActivity
package com.zhy.variousshapeimageview; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import com.zhy.view.RoundImageView; public class MainActivity extends Activity { private RoundImageView mQiQiu; private RoundImageView mMeiNv ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mQiQiu = (RoundImageView) findViewById(R.id.id_qiqiu); mMeiNv = (RoundImageView) findViewById(R.id.id_meinv); mQiQiu.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mQiQiu.setType(RoundImageView.TYPE_ROUND); } }); mMeiNv.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mMeiNv.setBorderRadius(90); } }); } }
最后的效果圖:
相關(guān)文章
android使用webwiew載入頁面使用示例(Hybrid App開發(fā))
Hybrid App 融合 Web App 的原理就是嵌入一個WebView組件,可以在這個組件中載入頁面,相當(dāng)于內(nèi)嵌的瀏覽器,下面是使用示例2014-03-03Android 一個日歷控件的實(shí)現(xiàn)代碼
本篇文章主要介紹了Android 一個日歷控件的實(shí)現(xiàn)代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05Android刮刮樂效果-proterDuffXfermode的示例代碼
這篇文章主要介紹了Android刮刮樂效果-proterDuffXfermode,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12Flutter構(gòu)建自定義Widgets的全過程記錄
在Flutter實(shí)際開發(fā)中,大家可能會遇到flutter框架中提供的widget達(dá)不到我們想要的效果,這時就需要我們?nèi)プ远xwidget,下面這篇文章主要給大家介紹了關(guān)于Flutter構(gòu)建自定義Widgets的相關(guān)資料,需要的朋友可以參考下2022-01-01Android中使用tcpdump、wireshark進(jìn)行抓包并分析技術(shù)介紹
這篇文章主要介紹了Android中使用tcpdump、wireshark進(jìn)行抓包并分析技術(shù)介紹,本文講解了下載并安裝tcpdump、pc上安裝wireshark等內(nèi)容,需要的朋友可以參考下2015-04-04Android中可以作為Log開關(guān)的一些操作及安全性詳解
Android的調(diào)試好伙伴Log在調(diào)試時非常有用,基本可以看Log而無需單點(diǎn)調(diào)試,尤其對實(shí)時大數(shù)據(jù)量的設(shè)備調(diào)試尤其有效,下面這篇文章就來給大家詳細(xì)介紹關(guān)于Android中可以作為Log開關(guān)的一些操作及安全性的相關(guān)資料,需要的朋友可以參考下。2017-12-12Android金額輸入框只允許輸入小數(shù)點(diǎn)后兩位效果
實(shí)現(xiàn)android 金額輸入框輸入小數(shù)點(diǎn)后兩位的效果也不是很復(fù)雜,只需要設(shè)置輸入框輸入的字符類型、設(shè)置InputFilter、設(shè)置輸入變化監(jiān)聽即可。這篇文章主要介紹了Android金額輸入框只允許輸入小數(shù)點(diǎn)后兩位 ,需要的朋友可以參考下2017-05-05Android 抽屜效果的導(dǎo)航菜單實(shí)現(xiàn)代碼實(shí)例
本篇文章主要介紹了Android 抽屜效果的導(dǎo)航菜單實(shí)現(xiàn)代碼實(shí)例,這種側(cè)滑的抽屜效果的菜單很好,有興趣的可以了解一下。2016-12-12