从布局XML文件中旋转ImageView源

54
我在布局中有一个ImageView:
<ImageView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:contentDescription="@string/image_divider"
        android:paddingBottom="8dp"
        android:paddingTop="4dp"
        android:scaleType="fitXY"
        android:src="@android:drawable/divider_horizontal_textfield" />

这是一个水平分隔线。我想将其旋转90度,以便我有一个垂直的分隔线。
有没有可能在布局中而不是在Activity类中实现这个效果?


你可以将高度设置为 layout_height="fill_parent",这样它就会在整个布局中被拉伸。 - thepoosh
如果您已经解决了问题,请接受/点赞该答案 :) - RPB
@thepoosh:源图像不是正方形。它是一个宽矩形,按照你所说的做法会导致一个细长的垂直矩形。 - mehrmoudi
3个回答

178

您可以使用自 API Level 11 开始提供的功能。

android:rotation="90"

最终放置的代码:

<ImageView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:rotation="90"
        android:contentDescription="@string/image_divider"
        android:paddingBottom="8dp"
        android:paddingTop="4dp"
        android:scaleType="fitXY"
        android:src="@android:drawable/divider_horizontal_textfield" />

1
谢谢,但是在我的ImageView中没有这样的属性!http://s15.postimage.org/gpit1dvrd/Untitled.png - mehrmoudi
1
我不同意:android:rotation 属性仅在API 11及以上版本中可用:http://developer.android.com/reference/android/R.attr.html#rotation - Jeje Doudou
2
@MehranMahmoudi 在API 10中无法通过编程方式旋转,你可以做的一件事是使用两个图像,一个带有90度旋转,另一个是默认的,:) - RPB
4
谢谢,现在它正常工作了。我原本期望旋转会反映在 XML 中,但运行项目后它被旋转了!! - Pankaj
请注意旋转是顺时针方向。 - ImMathan
显示剩余7条评论

3
在ImageView上添加“id”(如果没有自动生成):
 android:id="@+id/imageView"

使用“id”(Kotlin示例):
val imageView = findViewById<ImageView>(R.id.imageView)
imageView.setRotation(90f) // rotate 90 degree

1

您可以通过创建一个新的位图对象在代码中实现此功能。 请查看:http://android-er.blogspot.fr/2010/07/rotate-bitmap-image-using-matrix.html 特别是这个函数

Matrix matrix = new Matrix();
matrix.postScale(curScale, curScale);
matrix.postRotate(curRotate);

Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bmpWidth, bmpHeight, matrix, true);
myImageView.setImageBitmap(resizedBitmap);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接