Drawable围绕其中心Android旋转

我用以下代码得到了奇怪的结果:

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); 

什么是指定轴点(可绘制的中心)的正确方法?

感觉很蠢! 花了一些时间仔细阅读文档后才能使用它:

 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); 

请注意,如果您的对象具有非对称填充(例如,左侧填充为5px,右侧填充为0px),则此操作无效,因为填充被视为对象的一部分。 这意味着计算中心将被抵消。

解决此问题的一种方法是,如果出于布局原因使用填充,则使用边距而不是填充。 正如API所说的关于边距:“这个空间超出了这个观点的范围。” ( ViewGroup.MarginLayoutParams )

这意味着边距不会像填充那样旋转。

因为这个问题的标题是Drawable围绕它的中心旋转(我正在寻找它,没有find它并且必须自己实现它)想发布我的解决方案/答案。

我最终编写了自定义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; } }