Android——自定义view实现圆形图片并添加属性动画旋转

本文介绍如何在Android中创建一个自定义View,实现将图片显示为圆形,并添加属性动画来实现图片的旋转效果。通过自定义View的绘制过程,详细讲解了布局和动画的设置方法。

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();
            }
        });

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值