繁体   English   中英

将图像放置在布局android中

[英]place images inside a layout android

我想在布局内放置一些图像(在单击操作时触发)。 我必须放置它们,以免它们脱离父级布局。

单击布局时我用来添加新图像的代码:

LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
    ImageView image = new ImageView(this);
LinearLayout.LayoutParams coordinates = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
image.setLayoutParams(coordinates);
image.setImageResource(R.drawable.image);
layout.addView(image);

如果按布局,则必须看到imageView随机放置。

Random random = new Random();
int x = random.nextInt(layout.getWidth());
int y = random.nextInt(layout.getHeight());
image.setX(x);
image.setY(y);

但这不会做。 而且我也看到这些图像超出了我的布局。

您正在设置左上角的x和y-要显示图像的起点。 由于x / y值可以在右/下角,因此,在这种情况下,您的图像会超出布局。 请注意-x,y是绘制图像的起点。 您需要确保layoutWidth-x> = imageWidth和layoutHeight-y> = imageHeight。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM