Android: Rotate image in imageview by an angle

前端 未结 25 2604
野趣味
野趣味 2020-11-22 06:35

I am using the following code to rotate a image in ImageView by an angle. Is there any simpler and less complex method available.

ImageView iv = (ImageView)f         


        
25条回答
  •  既然无缘
    2020-11-22 07:16

    here's a nice solution for putting a rotated drawable for an imageView:

    Drawable getRotateDrawable(final Bitmap b, final float angle) {
        final BitmapDrawable drawable = new BitmapDrawable(getResources(), b) {
            @Override
            public void draw(final Canvas canvas) {
                canvas.save();
                canvas.rotate(angle, b.getWidth() / 2, b.getHeight() / 2);
                super.draw(canvas);
                canvas.restore();
            }
        };
        return drawable;
    }
    

    usage:

    Bitmap b=...
    float angle=...
    final Drawable rotatedDrawable = getRotateDrawable(b,angle);
    root.setImageDrawable(rotatedDrawable);
    

    another alternative:

    private Drawable getRotateDrawable(final Drawable d, final float angle) {
        final Drawable[] arD = { d };
        return new LayerDrawable(arD) {
            @Override
            public void draw(final Canvas canvas) {
                canvas.save();
                canvas.rotate(angle, d.getBounds().width() / 2, d.getBounds().height() / 2);
                super.draw(canvas);
                canvas.restore();
            }
        };
    }
    

    also, if you wish to rotate the bitmap, but afraid of OOM, you can use an NDK solution i've made here

提交回复
热议问题