圆形图片 ImageView
package com.example.m_evolution; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.widget.ImageView; public class CircleImageView extends ImageView { private Paint paint; public CircleImageView(Context context) { super(context); paint = new Paint(); } public CircleImageView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); paint = new Paint(); } public CircleImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); paint = new Paint(); } //显示时调用的函数 @Override protected void onDraw(Canvas canvas) { Drawable drawable = getDrawable(); //获取drawable if (drawable != null) { Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();//转换成bitmap Bitmap bitmap_circle = getCircleBitmap(bitmap); //将bitmap图片剪切成圆形 final Rect rectSrc = new Rect(0, 0, bitmap_circle.getWidth(), bitmap_circle.getHeight()); final Rect rectDest = new Rect(0,0,getWidth(),getHeight()); paint.reset(); canvas.drawBitmap(bitmap_circle, rectSrc, rectDest, paint); } else{ super.onDraw(canvas); } } //将bitmap图片剪切成圆形 private Bitmap getCircleBitmap(Bitmap bitmap) { Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),bitmap.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(output); final int color = 0xff424242; final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(color); int x = bitmap.getWidth(); canvas.drawCircle(x / 2, x / 2, x / 2, paint); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); canvas.drawBitmap(bitmap, rect, rect, paint); return output; } }