1.创建自定义view类
@SuppressLint("AppCompatCustomView")
public class Custom_show extends ImageView {
private Paint paint;
public Custom_show(Context context) {
super(context);
}
public Custom_show(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public Custom_show(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Drawable drawable = getDrawable();
if (drawable != null) {
Bitmap bitmap = getCircleBitmap(((BitmapDrawable)drawable).getBitmap());
canvas.drawBitmap(bitmap,0,0,paint);
} else {
super.onDraw(canvas);
}
}
private Bitmap getCircleBitmap(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
//计算圆的半径
int radius;
if (width > height) {
radius = height / 2;
} else {
radius = width / 2;
}
//新建画笔
paint = new Paint();
paint.setColor(Color.GRAY);
Bitmap b = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Bitmap.Config.ARGB_8888);
//使用canvas绘制一个bitmap处理
Canvas canvas = new Canvas(b);
canvas.drawCircle(width / 2, height / 2, radius, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, 0, 0, paint);
return b;
}
}
2.实现
布局
<smq.bw.com.smq0226.widget.Custom_show
android:id="@+id/custom"
android:layout_gravity="center"
android:src="@drawable/a"
android:scaleType="centerCrop"
android:layout_width="500dp"
android:layout_height="500dp" />
public class ShowActivity extends AppCompatActivity{
private Custom_show show;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show);
show = findViewById(R.id.custom);
Glide.with(this).load("https://avatar.csdnimg.cn/C/9/1/1_weixin_44310357.jpg").into(show);
show.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(show,"rotation",360f);
objectAnimator.setDuration(3000);
objectAnimator.start();
}
});
}
}