以编程方式将坐标设置为imageview的中心

问题描述 投票:0回答:1

我有坐标以编程方式将图像视图对齐。现在,图像已对齐,但是图像从该坐标开始,或者应该说该坐标成为其imageview的左上角,并且我想使其成为imageview的中心。如何使imageview的坐标中心?现在我正在这样做:

ImageView iv = new ImageView(this);

float x_coordinate = 256;
float y_coordinate = 350;
    iv.setX(x_coordinate);
    iv.setY(y_coordinate);

    iv.setImageResource(R.drawable.myimage);
    iv.setLayoutParams(new LayoutParams(
            LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT));
    mylayout.addView(iv);
android-layout layoutparams
1个回答
1
投票

我没有找到简单的一线解决方案,但我通过以下步骤解决了我的问题。这里的Place是我的模型类,其中的getX_Cord()和getY_Cord()返回图像的x和y坐标,并且您必须将图像保存在要在屏幕上设置大小的可绘制文件夹中,在这种情况下,这是R.drawable.placeImage。

// display parameters
Point size = new Point();
Display display = getWindowManager().getDefaultDisplay();
display.getSize(size);
width = size.x;
height = size.y;

final Place place = roomPlace.get(i);

Drawable d = getResources().getDrawable(R.drawable.placeImage);
int y = d.getIntrinsicHeight() / 2;
int x = d.getIntrinsicWidth() / 2;

placeImage.setX((place.getX_Cord() * width) - x);
placeImage.setY((place.getY_Cord() * height) - y);

也许有人会得到更合适的解决方案,但是我这样做解决了我的问题。

© www.soinside.com 2019 - 2024. All rights reserved.