Android 自定義圓形頭像1.0

兩種方式? ?1?本地獲取圖片? 2?通過網(wǎng)絡(luò)獲取網(wǎng)絡(luò)圖片?通過BitmapShader轉(zhuǎn)為圓形圖片

兩種方式的實現(xiàn)方法相同,只是圖片獲取不同

一、從本地資源獲取圖片

//獲取本地資源

Resources resources = getResources();

//拿到本地圖片

Bitmap bitmap = BitmapFactory.decodeResource( resources, R.mipmap.cut );

二、從網(wǎng)絡(luò)獲取圖片

//獲取圖片的網(wǎng)絡(luò)路徑

String commentHeadPic = resultBean.getCommentHeadPic();

//獲取網(wǎng)絡(luò)圖片

try {

????????new Thread(? ){

????????????????@Override

? ? ? ? ? ? ? ? ?public void run() {

????????????????????????super.run();

????????????????????????URL url =null;

????????????????????????try {

????????????????????????????//統(tǒng)一資源定位符

? ? ? ? ? ? ? ????????????????? url =new URL(commentHeadPic );

????????????????????????????????//HttpURLConnection請求網(wǎng)絡(luò)

? ? ? ? ? ? ????????????????? ? HttpURLConnection httpURLConnection = (HttpURLConnection)? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?????????url.openConnection();

????????????????????????????????//設(shè)置超時

? ? ? ? ? ? ? ? ????????????????httpURLConnection.setConnectTimeout(5000 );

????????????????????????????????httpURLConnection.connect();

????????????????????????????????//獲取流

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? InputStream inputStream = httpURLConnection.getInputStream();

????????????????????????????????//轉(zhuǎn)為為Bitmap格式

? ? ? ? ? ? ? ? ????????????????Bitmap bitmap = BitmapFactory.decodeStream( inputStream );

????????????????????????????????//自定義view設(shè)置bitmap

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ivPic.setBitmap( bitmap );??

? ??????????????????????????????inputStream .clone

????????????????}catch (Exception e) {

????????????????????????e.printStackTrace();

????????????????}

????????????}

????????}.start();//啟動線程

? ? ? }catch (Exception e){

????????????String message = e.getMessage();

????????????Log.i(TAG,"onBindViewHolder: "+message );

}

圖片獲取成功后?

創(chuàng)建CircularView類?繼承view

//全局變量

private Bitmapbitmap;

private BitmapShadershader;

private int radius;//半徑

三個構(gòu)造方法?無需變動

public void setBitmap(Bitmap bitmap) {

????????????this.bitmap = bitmap;

}

↑? 這是上邊通過網(wǎng)絡(luò)獲取圖片?設(shè)置Bitmap的方法

測量?重寫onMeasure()

//獲取當(dāng)前控件的最小值

int width = Math.min( getMeasuredWidth(), getMeasuredHeight() );

radius = width/2;//得到半徑

繪制?重寫onDraw()

if (bitmap !=null) {

? ? ? shader =new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP );

? ? ? ?//創(chuàng)建畫筆

? ? ????Paint paint =new Paint();

????????//抗鋸齒

? ????? paint.setAntiAlias(true );

????????//設(shè)置shader

? ????? paint.setShader(shader );

? ? ? ? //繪制圓形

????????canvas.drawCircle(radius,radius,radius,paint);

}

僅供參考

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

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

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