Android开发圆形ImageView实现
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android开发圆形ImageView实现相关的知识,希望对你有一定的参考价值。
1、自定义属性,在value文件夹下新建attrs文件,声明如下属性
<declare-styleable name="CircleImageView"> <attr name="border_color" format="color"/> <attr name="border_width" format="dimension"/> </declare-styleable>
2、继承ImageView ,重写构造和ondraw方法
public class CircleImageView extends AppCompatImageView { private int borderColor; private int borderWidth; private final static int DEFAULT_COLOR = Color.BLACK; private final static int DEFAULT_BORDER_WIDTH = 0; private Paint mPaint; public CircleImageView(Context context) { this(context,null); } public CircleImageView(Context context, @Nullable AttributeSet attrs) { this(context, attrs,0); } public CircleImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.CircleImageView); borderColor = typedArray.getColor(R.styleable.CircleImageView_border_color, DEFAULT_COLOR); borderWidth = typedArray.getDimensionPixelSize(R.styleable.CircleImageView_border_width, DEFAULT_BORDER_WIDTH); borderWidth = dp2px(context,borderWidth); mPaint = new Paint(); typedArray.recycle(); } public int dp2px(Context ctx,int dp) { float scale = ctx.getResources().getDisplayMetrics().density; return (int) (dp * scale + 0.5); } @Override protected void onDraw(Canvas canvas) { Drawable drawable = getDrawable(); if (drawable != null) { Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap(); Bitmap circleBitmap = getCircleBitmap(bitmap); Rect srcRect = new Rect(0,0,circleBitmap.getWidth(),circleBitmap.getHeight()); Rect dstRect = new Rect(0,0,getWidth(),getHeight()); mPaint.reset(); canvas.drawBitmap(circleBitmap,srcRect,dstRect,mPaint); }else { super.onDraw(canvas); } } private Bitmap getCircleBitmap(Bitmap bitmap) { Bitmap circleBitmap = Bitmap.createBitmap(bitmap.getWidth(),bitmap.getHeight(),Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(circleBitmap); mPaint.setAntiAlias(true); canvas.drawARGB(0,255,255,255); mPaint.setColor(borderColor); int radius = bitmap.getWidth() < bitmap.getHeight()? bitmap.getWidth():bitmap.getHeight(); canvas.drawCircle(radius/2,radius/2,radius/2-borderWidth,mPaint); mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); Rect rect = new Rect(0,0,bitmap.getWidth(),bitmap.getHeight()); canvas.drawBitmap(bitmap,rect,rect,mPaint); mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OVER)); canvas.drawCircle(radius/2,radius/2,radius / 2,mPaint); return circleBitmap; } }
3、引入CircleImageView
<com.mydemo.view.CircleImageView android:layout_width="100dp" android:layout_height="100dp" android:src="@drawable/logo" app:border_color="#ffff00" app:border_width="1dp" />
以上是关于Android开发圆形ImageView实现的主要内容,如果未能解决你的问题,请参考以下文章
Android开发之自定义圆角矩形图片ImageView的实现