在我们的开发中时常要用到圆形的ImageView,今天就用几种方法实现圆形的图片,希望对大家有帮助!
1.用谷歌自带RoundBitmapDrawable制作,代码如下:
private void setBitmapCircle() {
Bitmap b=BitmapFactory.decodeResource(getResources(),R.drawable.bag);
RoundedBitmapDrawable r= RoundedBitmapDrawableFactory.create(getResources(),b);
r.setCircular(true);
imageView.setImageDrawable(r);
}
优点:方便快捷,直接用自带的Api完成,不用自己自定义控件。
局限性:设置为圆形的图片必须是宽度和长度相等,不然没有效果。
2.自定义圆形控件
直接上代码!!
public CircleImageView(Context context) {
this(context,null);
}
public CircleImageView(Context context, AttributeSet attrs) {
this(context, attrs,0);
}
public CircleImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
private Bitmap bitmap;
private Rect bitmapRect=new Rect();
private PaintFlagsDrawFilter pdf=new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG|Paint.FILTER_BITMAP_FLAG);
private Paint paint = new Paint();
{
paint.setStyle(Paint.Style.STROKE);
paint.setFlags(Paint.ANTI_ALIAS_FLAG);
paint.setAntiAlias(true);// 设置画笔的锯齿效果。 true是去除,大家一看效果就明白了
}
private Bitmap mDstB=null;
private PorterDuffXfermode xfermode=new PorterDuffXfermode(PorterDuff.Mode.MULTIPLY);
public void setImageBitmap(Bitmap bitmap)
{
this.bitmap=bitmap;
try {
if(android.os.Build.VERSION.SDK_INT>=11)
{
setLayerType(LAYER_TYPE_SOFTWARE, null);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private Bitmap makeDst(int w, int h)
{
Bitmap bm = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bm);
Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
p.setColor(Color.parseColor("#ffffffff"));
c.drawOval(new RectF(0, 0, w, h), p);
return bm;
}
@Override
protected void onDraw(Canvas canvas) {
if(null==bitmap)
{
return;
}
if(null==mDstB)
{
mDstB=makeDst(getWidth(), getHeight());
}
bitmapRect.set(0, 0, getWidth(), getHeight());
canvas.save();
canvas.setDrawFilter(pdf);
canvas.drawBitmap(mDstB, 0, 0, paint);
paint.setXfermode(xfermode);
canvas.drawBitmap(bitmap, null, bitmapRect, paint);
paint.setXfermode(null);
canvas.restore();
}
优点:任何图片都可以实现圆形图片
局限性:在自定义view中制作过程麻烦。。。。。。