兩種方式? ?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);
}
僅供參考