【问题标题】:How to rotate a drawable but not the imageView itself?如何旋转drawable而不是imageView本身?
【发布时间】:2014-03-07 22:27:09
【问题描述】:

我有一个内部带有可绘制对象的图像视图。这个drawable是一个类似于正在进行的对话框的环:

加载环:

<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="ring"
    android:innerRadiusRatio="3"
    android:thicknessRatio="8"
    android:useLevel="false">
    <size
        android:width="20dip"
        android:height="20dip"/>

    <gradient
        android:type="sweep"
        android:useLevel="false"
        android:startColor="#4c737373"
        android:centerColor="#4c737373"
        android:centerY="0.50"
        android:endColor="#ffffffff"/>
</shape>

为了旋转这个环,我创建了一个像这样的旋转动画:

<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:toDegrees="359"
    android:pivotX="50%"
    android:pivotY="50%"
    android:repeatCount="infinite"
    android:duration="1000"
    android:interpolator="@android:anim/linear_interpolator" />

但是当我在 imageView 上应用动画时:

this.cameraView.setAnimation(AnimationUtils.loadAnimation(this,R.anim.loadinganimation));

所有的 imageView 都在旋转。我只想旋转环(imageview 的 src)我怎么能做到这一点?

谢谢

【问题讨论】:

    标签: android drawable android-animation


    【解决方案1】:
    // load the origial BitMap (500 x 500 px)
    Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
           R.drawable.android);
    
    int width = bitmapOrg.width();
    int height = bitmapOrg.height();
    
    // createa matrix for the manipulation
    Matrix matrix = new Matrix();
    
    // rotate the Bitmap
    matrix.postRotate(45);
    
    // recreate the new Bitmap
    Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0,
                      width, height, matrix, true);
    
    // make a Drawable from Bitmap to allow to set the BitMap
    // to the ImageView, ImageButton or what ever
    BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);
    
    // set the Drawable on the ImageView
    imageView.setImageDrawable(bmd);
    

    详情请看这里。

    http://www.anddev.org/resize_and_rotate_image_-_example-t621.html

    【讨论】:

    • 此解决方案适用于一次性轮换。我不确定它是否对无限(及时)轮换有用。
    【解决方案2】:

    制作两个分开的视图并使用FrameLayout 来包含它们。这样您就可以将动画应用到环而不是其他小部件。

    编辑:

    我猜你是用android:src 把形状放在ImageView 里面,用android:background 设置别的东西。如果是这种情况,您可以尝试使用ImageView,而不是:

    <FrameLayout>
      <ImageView with the background>
      <ImageView with JUST the shape>
    </FrameLayout>
    

    <FrameLayout android:background="blah">
      <ImageView with JUST the shape>
    </FrameLayout>
    

    【讨论】:

    • 你能详细说明一下你的答案吗? “制作两个分开的视图”是什么意思,两个视图用于什么?
    • 好的,感谢您的更新。我已经在使用这个“技巧”,但我希望有一种更清洁的方法。无论如何都赞成并在接受之前稍等片刻;)