android圆形的ImageView

来源:互联网 发布:股票指标公式源码大全 编辑:程序博客网 时间:2024/04/29 02:01

android圆形的ImageView

view plainprint?
  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. }  


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

原创粉丝点击