以编程方式旋转可绘制或视图

Ala*_*Lai 13 java android rotation

<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="@drawable/your_drawable"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="360" />
Run Code Online (Sandbox Code Playgroud)

我想以编程方式旋转drawable.

我该怎么办?

这是我的回调

private class RotateListener implements RotateGestureDetector.OnRotateGestureListener{
    @Override
    public boolean onRotate(MotionEvent event1, MotionEvent event2,
            double deltaAngle) {

        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

deltaangle不大于0.1,我不知道什么是提取价值.

jlo*_*pez 37

以下代码围绕其中心旋转ImageView:

ImageView myImageView = (ImageView)findViewById(R.id.my_imageview);

AnimationSet animSet = new AnimationSet(true);
animSet.setInterpolator(new DecelerateInterpolator());
animSet.setFillAfter(true);
animSet.setFillEnabled(true);

final RotateAnimation animRotate = new RotateAnimation(0.0f, -90.0f,
    RotateAnimation.RELATIVE_TO_SELF, 0.5f, 
    RotateAnimation.RELATIVE_TO_SELF, 0.5f);

animRotate.setDuration(1500);
animRotate.setFillAfter(true);
animSet.addAnimation(animRotate);

myImageView.startAnimation(animSet);
Run Code Online (Sandbox Code Playgroud)

  • 无论如何我还能再投票5次吗? (3认同)

and*_*per 16

这是一个很好的解决方案,为imageView放置一个旋转的drawable:

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;
}
Run Code Online (Sandbox Code Playgroud)

用法:

Bitmap b=...
float angle=...
final Drawable rotatedDrawable = getRotateDrawable(b,angle);
root.setImageDrawable(rotatedDrawable);
Run Code Online (Sandbox Code Playgroud)

另一种选择:

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();
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

另外,如果你想旋转位图,但是害怕OOM,你可以使用我在这里制作的NDK解决方案