圆形ImageView

方法1

public class RoundImageView extends ImageView{

   int width=0,height=0;
   //半径
   int radius=0;
   Paint paint;
   BitmapShader shader;
   Matrix matrix;
   
   public RoundImageView(Context context, AttributeSet attrs, int defStyle) {
      super(context, attrs, defStyle);
   }

   public RoundImageView(Context context, AttributeSet attrs) {
      super(context, attrs);
      paint = new Paint();
      paint.setAntiAlias(true);
   }
   
   @Override
   protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
      super.onMeasure(widthMeasureSpec, heightMeasureSpec);
      width = Math.min(getMeasuredWidth(), getMeasuredHeight());
      radius = width/2;
      setMeasuredDimension(width, width);
   }
   
   
   @Override
   protected void onDraw(Canvas canvas) {
      if (getDrawable()==null) {
         return;
      }
      
      Bitmap bmp=null;
      if (getDrawable() instanceof BitmapDrawable) {
         BitmapDrawable bd = (BitmapDrawable) getDrawable();
         bmp = bd.getBitmap();
      }
      
      shader = new BitmapShader(bmp, TileMode.CLAMP, TileMode.CLAMP);
      float scale =1f;
      int size = Math.min(bmp.getWidth(), bmp.getHeight());
      scale =width*1.0f/size;
      matrix = new Matrix();
      matrix.setScale(scale, scale);
      shader.setLocalMatrix(matrix);
      paint.setShader(shader);
      
      canvas.drawCircle(radius, radius, radius, paint);
   }
}


方法2
public class RoundDrawable extends Drawable {

   private Paint mPaint;
   private int mWidth;
   private Bitmap mBitmap;

   public RoundDrawable(Bitmap bitmap) {
      mBitmap = bitmap;
      BitmapShader bitmapShader = new BitmapShader(bitmap, TileMode.CLAMP,
            TileMode.CLAMP);
      mPaint = new Paint();
      mPaint.setAntiAlias(true);
      mPaint.setShader(bitmapShader);
      mWidth = Math.min(mBitmap.getWidth(), mBitmap.getHeight());
   }

   @Override
   public void draw(Canvas canvas) {
      canvas.drawCircle(mWidth / 2, mWidth / 2, mWidth / 2, mPaint);
   }

   @Override
   public int getIntrinsicWidth() {
      return mWidth;
   }

   @Override
   public int getIntrinsicHeight() {
      return mWidth;
   }

   @Override
   public void setAlpha(int alpha) {
      mPaint.setAlpha(alpha);
   }

   @Override
   public void setColorFilter(ColorFilter cf) {
      mPaint.setColorFilter(cf);
   }

   @Override
   public int getOpacity() {
      return PixelFormat.TRANSLUCENT;
   }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值