android圆形的ImageView

android圆形的ImageView

  1. package com.example.testsam;  
  2.   
  3. import android.content.Context;  
  4. import android.graphics.Bitmap;  
  5. import android.graphics.Bitmap.Config;  
  6. import android.graphics.Canvas;  
  7. import android.graphics.Paint;  
  8. import android.graphics.PorterDuff.Mode;  
  9. import android.graphics.PorterDuffXfermode;  
  10. import android.graphics.Rect;  
  11. import android.graphics.drawable.BitmapDrawable;  
  12. import android.graphics.drawable.Drawable;  
  13. import android.util.AttributeSet;  
  14. import android.widget.ImageView;  
  15.   
  16. /** 
  17.  * 圆形的Imageview 
  18.  * @since 2012-11-02 
  19.  *  
  20.  * @author bingyang.djj 
  21.  *  
  22.  */  
  23. public class CircleImageView extends ImageView {  
  24.     private Paint paint = new Paint();  
  25.   
  26.     public CircleImageView(Context context) {  
  27.         super(context);  
  28.     }  
  29.   
  30.     public CircleImageView(Context context, AttributeSet attrs) {  
  31.         super(context, attrs);  
  32.     }  
  33.   
  34.     public CircleImageView(Context context, AttributeSet attrs, int defStyle) {  
  35.         super(context, attrs, defStyle);  
  36.     }  
  37.   
  38.     @Override  
  39.     protected void onDraw(Canvas canvas) {  
  40.   
  41.         Drawable drawable = getDrawable();  
  42.         if (null != drawable) {  
  43.             Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();  
  44.             Bitmap b = toRoundCorner(bitmap, 14);  
  45.             final Rect rect = new Rect(00, b.getWidth(), b.getHeight());  
  46.             paint.reset();  
  47.             canvas.drawBitmap(b, rect, rect, paint);  
  48.   
  49.         } else {  
  50.             super.onDraw(canvas);  
  51.         }  
  52.     }  
  53.   
  54.     private Bitmap toRoundCorner(Bitmap bitmap, int pixels) {  
  55.         Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),  
  56.                 bitmap.getHeight(), Config.ARGB_8888);  
  57.         Canvas canvas = new Canvas(output);  
  58.           
  59.         final int color = 0xff424242;  
  60.         final Rect rect = new Rect(00, bitmap.getWidth(), bitmap.getHeight());  
  61.         paint.setAntiAlias(true);  
  62.         canvas.drawARGB(0000);  
  63.         paint.setColor(color);  
  64.         int x = bitmap.getWidth();  
  65.         canvas.drawCircle(x / 2, x / 2, x / 2, paint);  
  66.         paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));  
  67.         canvas.drawBitmap(bitmap, rect, rect, paint);  
  68.         return output;  
  69.     }  
  70. }  


可以直接当组件在布局文件中使用了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值