圆形ImageView的简单实现
实现思路:
图层混合模式:
具体实现
1 public class CircleImageView extends ImageView { 2 //画笔 3 private Paint paint; 4 5 public CircleImageView(Context context) { 6 super(context); 7 } 8 9 public CircleImageView(Context context, AttributeSet attrs) { 10 super(context, attrs); 11 paint = new Paint(); 12 } 13 //画圆形图片 14 @Override 15 protected void onDraw(Canvas canvas) { 16 Drawable drawable = getDrawable(); 17 if(drawable!=null){ 18 Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap(); 19 //获得圆形的位图 20 Bitmap b = getCilrcleBitmap(bitmap); 21 //绘制的区域 22 Rect rect = new Rect(0,0,b.getWidth(),b.getHeight()); 23 //绘制的大小(可以稍大一点,为边框预留) 24 Rect rectDest = new Rect(0,0,getWidth(),getHeight()); 25 //绘制 26 canvas.drawBitmap(b,rect,rectDest,paint); 27 28 }else{ 29 super.onDraw(canvas); 30 } 31 } 32 //获取圆形图片 33 private Bitmap getCilrcleBitmap(Bitmap bitmap){//源图像 34 Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),bitmap.getHeight(), Bitmap.Config.ARGB_8888); 35 Canvas canvas = new Canvas(output); 36 //打开抗锯齿 37 paint.setAntiAlias(true); 38 paint.setColor(Color.RED); 39 //设置目标图像区域外的颜色,(透明度,红色,绿色,蓝色) 40 //canvas.drawARGB(90,90,0,0); 41 //绘制目标图像 42 canvas.drawCircle(bitmap.getWidth()/2,bitmap.getHeight()/2,bitmap.getWidth()/2,paint); 43 //设置图像混合模式 44 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); 45 //绘制区域 46 Rect rect = new Rect(0,0,bitmap.getWidth(),bitmap.getHeight()); 47 //绘制位置 48 // Rect rectDest = new Rect(0,0,50,50); 49 50 canvas.drawBitmap(bitmap,rect,rect,paint); 51 paint.reset(); 52 return output; 53 } 54 }
具体效果:
1 <com.example.king.myapplication.CircleImageView 2 android:src="@drawable/three" 3 android:layout_gravity="center" 4 android:layout_width="wrap_content" 5 android:layout_height="wrap_content" 6 android:id="@+id/circleImageView" />
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步