(这是对 Android: How do you scale multiple views together? 的后续)
我的任务是在 Android 上移植一个 iPhone/iPad 应用程序,该应用程序包含一个简单的 ImageView ,动画按绝对位置在顶部分层。虽然这在 iOS 上听起来相当容易,您只需定位几个可能的屏幕尺寸,但在 Android 上却变得相当困惑。
我当前的设置是这样的:一个 RelativeLayout,我将我的主(背景)图像放在 left = 0,top = 0 和多个 ViewFlipper 实例用作“动画容器”,相对于左上角定位父布局实例。
这种方法有两个基本问题:
一旦布局的实际大小与主背景图像的大小不匹配,定位的“动画”就会错位。
定位的“动画”也有错误的大小,因为它们通常有自己周围的“足够空间”,Android 不会缩放它们以适应 RelativeLayout(也不会相对于原始布局缩放它们背景。
由于动画本身必须是交互式的,因此无法将所有动画放置在与主(背景)图像大小相同的透明层上,因为它们会彼此重叠,并且只有最上面的将是交互式的。
我想到了不同的解决方案:
要获得主图像的比例因子,我可以检索它的
measuredWidth
和measuredHeight
并将其设置为原始width 的关系
和高度
的 View 。然后我将使用此比例因子进行自定义定位并最终进行自定义缩放。但是,显然measuredWidth/-Height
属性只在 onMeasure() 期间设置。 call,这个是在构建完组件树之后调用的,完全不知道这个方案是否可行。实现我自己的布局管理器并相应地缩放/定位 View 。我查看了
RelativeLayout
的实现,但不得不承认 onMeasure()方法让我有点害怕。
如果是我,你会怎么做?有什么我还没有考虑到的吗?
提前致谢。
最佳答案
好吧,回答我自己的问题 - 这是我解决问题的方式:
- 我使用
ImageView.setScaleType(ScaleType.FIT_START)
将背景图片放在 - 我这样计算背景图片的比例因子:
ImageView
的顶部
WindowManager mgr = (WindowManager) context .getSystemService(Context.WINDOW_SERVICE); DisplayMetrics metrics = new DisplayMetrics(); mgr.getDefaultDisplay().getMetrics(metrics); Drawable image = context.getResources().getDrawable(R.drawables.someImage); float scale = metrics.widthPixels / (float) image.getIntrinsicWidth();
- 最后,我在自定义 ImageView 类中使用了这个比例,该类加载叠加层以正确定位和缩放 View :
public class OverlayImage extends ImageView { private int imgWidth, imgHeight; private final float scale; public OverlayImage(Context context, int xPos, int yPos, float scale) { super(context); this.scale = scale; LayoutParams animParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); animParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT); animParams.addRule(RelativeLayout.ALIGN_PARENT_TOP); animParams.leftMargin = (int) (scale * xPos); animParams.topMargin = (int) (scale * yPos); setLayoutParams(animParams); Drawable dr = context.getResources().getDrawable(R.id.someImage); setBackgroundDrawable(dr); imgWidth = dr.getIntrinsicWidth(); imgHeight = dr.getIntrinsicHeight(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension((int) (scale * imgWidth), (int) (scale * imgHeight)); } }
关于android - 相对缩放 View 及其分层 subview ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6500156/