我使用以下代码得到了奇怪的结果:
iv = (ImageView) findViewById(R.id.iv);
iv.setImageResource(R.drawable.spinner_white_76);
Animation a = new RotateAnimation(0.0f, 360.0f,
Animation.RELATIVE_TO_SELF, iv.getDrawable()
.getIntrinsicWidth() / 2, Animation.RELATIVE_TO_SELF,
iv.getDrawable().getIntrinsicHeight() / 2);
a.setRepeatCount(-1);
a.setDuration(1000);
iv.startAnimation(a);
指定轴点(可绘制的中心)的正确方法是什么?
答案 0 :(得分:59)
感觉很蠢!在花了一些时间仔细阅读文档之后才开始工作:
Animation a = new RotateAnimation(0.0f, 360.0f,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
0.5f);
a.setRepeatCount(-1);
a.setDuration(1000);
答案 1 :(得分:6)
请注意,如果您的对象具有非对称填充(例如,左边填充为5px,右边填充为0px),则此操作无效,因为填充被视为对象的一部分。这意味着计算中心将被抵消。
如果您出于布局原因使用填充,则可以使用边距而不是填充。正如API所说的关于边距:“这个空间超出了这个观点的范围。” (ViewGroup.MarginLayoutParams)
这意味着边距不会像填充一样旋转。
答案 2 :(得分:3)
因为这个问题的标题是 Drawable 围绕它的中心旋转(我正在搜索它,没有找到它并且必须自己实现它)想发布我的解决方案/答案。
我最终编写了自定义drawable,可以包装任何drawable并允许其旋转。这是代码:
public class RotatableDrawable extends DrawableWrapper {
private float rotation;
private Rect bounds;
private ObjectAnimator animator;
private long defaultAnimationDuration;
public RotatableDrawable(Resources resources, Drawable drawable) {
super(vectorToBitmapDrawableIfNeeded(resources, drawable));
bounds = new Rect();
defaultAnimationDuration = resources.getInteger(android.R.integer.config_mediumAnimTime);
}
@Override
public void draw(Canvas canvas) {
copyBounds(bounds);
canvas.save();
canvas.rotate(rotation, bounds.centerX(), bounds.centerY());
super.draw(canvas);
canvas.restore();
}
public void rotate(float degrees) {
rotate(degrees, defaultAnimationDuration);
}
public void rotate(float degrees, long millis) {
if (null != animator && animator.isStarted()) {
animator.end();
} else if (null == animator) {
animator = ObjectAnimator.ofFloat(this, "rotation", 0, 0);
animator.setInterpolator(new AccelerateDecelerateInterpolator());
}
animator.setFloatValues(rotation, degrees);
animator.setDuration(millis).start();
}
@AnimatorSetter
public void setRotation(float degrees) {
this.rotation = degrees % 360;
invalidateSelf();
}
/**
* Workaround for issues related to vector drawables rotation and scaling:
* https://code.google.com/p/android/issues/detail?id=192413
* https://code.google.com/p/android/issues/detail?id=208453
*/
private static Drawable vectorToBitmapDrawableIfNeeded(Resources resources, Drawable drawable) {
if (drawable instanceof VectorDrawable) {
Bitmap b = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
drawable.setBounds(0, 0, c.getWidth(), c.getHeight());
drawable.draw(c);
drawable = new BitmapDrawable(resources, b);
}
return drawable;
}
}