android位置视图里面的布局

时间:2013-05-21 11:33:17

标签: android android-layout

我的活动有一个1280x800像素的背景图片。我使用android:scaleType="centerCrop"设置了它。

在背景图像上描绘了一个旗杆,我需要在旗杆上方放置另一个图像(“旗帜”)。

如果设备的屏幕尺寸正好是1280x800,那么“flag”的位置将是(850,520)。但屏幕大小可能会有所不同,Android会根据centerCrop标记对背景图像进行缩放和移位。因此,我需要以某种方式指定比例并转移到“标志”图像,使其放置在旗杆上方。

我检查了ImageView.java,发现scaleType用于设置private Matrix mDrawMatrix。但我没有读取此字段的权限,因为它是私有的。

所以,给定

@Override
public void onGlobalLayout()
{
    ImageView bg = ...;
    ImageView flag = ...;
    int bgImageWidth = 1280;
    int bgImageHeight = 800;
    int flagPosX = 850;
    int flagPosY = 520;
    // What should I do here to place flag nicely?
}

2 个答案:

答案 0 :(得分:0)

您可以看到屏幕的大小(context.getResources().getDisplayMetrics().widthPixelscontext.getResources().getDisplayMetrics().heightPixels;)并计算图片中可见的内容,例如您可以执行此类操作(尚未对其进行过测试,但你应该明白这个想法):

private void placeFlag(Context context) {
    ImageView bg = new ImageView(context);
    ImageView flag = new ImageView(context);
    int bgImageWidth = 1280;
    int bgImageHeight = 800;
    int flagPosX = 850;
    int flagPosY = 520;

    int screenWidth = context.getResources().getDisplayMetrics().widthPixels;
    int screenHeight = context.getResources().getDisplayMetrics().heightPixels;

    //calculate the proportions between the width of the bg and the screen
    double widthScale = (double) bgImageWidth / (double) screenWidth;
    double heightScale = (double) bgImageHeight / (double) screenHeight;

    //see the real scale used, it will be the maximum between the 2 values because you are using crop
    double realScale = Math.max(widthScale, heightScale);
    //calculate the position for the flag
    int flagRealX = (int) (flagPosX * realScale);
    int flagRealY = (int) (flagPosY * realScale);
}

此外,您应该在方法onGlobalLayout中执行此操作,如果您想要自定义视图,可以在onCreate()或构造函数内部执行此操作。

答案 1 :(得分:0)

你可以在这里使用LayerDrawable方法在其中创建一个可绘制的图像是静态的(在其中你可以在custom_drawable.xml中的背景图像上设置背景图像和图标,并且可以在活动中将该文件用作单个drawable)。参考转到android developer。除此以外 对于根据不同device resolution放置图像放在不同的可绘制文件夹中的比例问题,也可以设计不同的布局。