Android-旋转按钮内的图像
我想在点击按钮时旋转按钮内的图像。我试过只使用ImageView,但为了便于访问,我需要使用按钮而不是ImageView 单击之前: 这里的向下箭头是按钮背景 单击后: 点击按钮显示额外数据,背景箭头旋转。如何在单击时设置按钮背景的动画和旋转 布局代码供参考:Android-旋转按钮内的图像,android,button,android-animation,Android,Button,Android Animation,我想在点击按钮时旋转按钮内的图像。我试过只使用ImageView,但为了便于访问,我需要使用按钮而不是ImageView 单击之前: 这里的向下箭头是按钮背景 单击后: 点击按钮显示额外数据,背景箭头旋转。如何在单击时设置按钮背景的动画和旋转 布局代码供参考: <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical" >
<LinearLayout
android:id="@+id/cases_actions_row"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="horizontal" >
<Button
android:id="@+id/case_action_item_1"
style="@style/card_action_button"
android:layout_height="wrap_content"
android:layout_width="wrap_content" />
<Button
android:id="@+id/case_action_item_2"
style="@style/card_action_button"
android:layout_height="wrap_content"
android:layout_width="wrap_content" />
</LinearLayout>
<Button
android:id="@+id/cases_expand_button"
style="@style/card_action_button"
android:layout_height="20dp"
android:layout_width="20dp"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:background="@drawable/ic_arrow" />
</RelativeLayout>
您可以在按钮中将位图设置为背景
Matrix matrix = new Matrix();
matrix.postRotate(90);
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmapOrg,width,height,true);
Bitmap rotatedBitmap = Bitmap.createBitmap(scaledBitmap , 0, 0, scaledBitmap .getWidth(), scaledBitmap .getHeight(), matrix, true);
BitmapDrawable bdrawable = new BitmapDrawable(context.getResources(),bitmap);
button.setBackground(bdrawable);
首先从任何源获取位图,然后旋转它,然后在按钮中将其设置为背景
Matrix matrix = new Matrix();
matrix.postRotate(90);
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmapOrg,width,height,true);
Bitmap rotatedBitmap = Bitmap.createBitmap(scaledBitmap , 0, 0, scaledBitmap .getWidth(), scaledBitmap .getHeight(), matrix, true);
BitmapDrawable bdrawable = new BitmapDrawable(context.getResources(),bitmap);
button.setBackground(bdrawable);
最简单的方法是旋转整个按钮(正如Frank N.Stein在评论中所建议的那样,
ImageButton
可能是最合适的,尽管没有什么可以阻止您使用不同的小部件)
有几种方法可以旋转按钮,但是ViewPropertyAnimator
可能也是最简单的方法:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
float deg = button.getRotation() + 180F;
button.animate().rotation(deg).setInterpolator(new AccelerateDecelerateInterpolator());
}
});
编辑:顺便说一句,如果您希望箭头反转其原始动画,可以尝试:
float deg = (button.getRotation() == 180F) ? 0F : 180F;
而不是
float deg=button.getRotation()+180F代码>我试过只使用ImageView,但出于可访问性目的,我需要使用按钮而不是ImageView。
。。。或者使用一个图片按钮,弗兰克。我会检查这些文件。我可以在更改图像时添加动画吗?ImageButton
继承自ImageView
。但是看起来像一个按钮。因此,如果它在图像视图
(你这么说的话)上工作,它也会在图像按钮
上工作。旋转整个按钮也会旋转按钮背景,如果它有一个是,但这在提问者的情况下不是问题