繁体   English   中英

如何在屏幕上的特定位置显示UIImage?

[英]How do I display a UIImage at a specific place on the screen?

我正在尝试让UIImage显示在屏幕上的某个位置。 我在下面的代码中尝试了initWithFrame,但它仍显示在左上角。 我该怎么办呢?

UIImage *headImage = [UIImage imageNamed:@"head"];
UIImageView *headView = [[[UIImageView alloc] initWithImage:headImage] initWithFrame:CGRectMake(200.0, 200.0, 400.0, 500.0)];
[self.view addSubview:headView];

请执行以下操作:创建图像视图设置框架

UIImage *headImage = [UIImage imageNamed:@"head"];
UIImageView *headView = [[UIImageView alloc] initWithImage:headImage];
headView.frame = CGRectMake(200.0, 200.0, 400.0, 500.0);
[self.view addSubview:headView];

干杯!

您不能两次调用init 将您的代码更改为:

UIImage *headImage = [UIImage imageNamed:@"head"];
UIImageView *headView = [[[UIImageView alloc] initWithFrame:CGRectMake(200.0, 200.0, 400.0, 500.0)];
headView.image = headImage;
[self.view addSubview:headView];

如果您希望图像视图具有特定大小,则其他答案也很好。 但是,如果您希望图像视图的大小与图像大小匹配并将图像视图放置在特定位置,则应该执行以下操作:

UIImage *headImage = [UIImage imageNamed:@"head"];
UIImageView *headView = [[[UIImageView alloc] initWithImage:headImage] 
CGRect frame = headView.bounds;
frame.origin.x = 200;
frame.origin.y = 400;
headView.frame = frame;
[self.view addSubview:headView];

即使您更改图像的大小,此代码也可以正常工作。

如果不需要更改图像大小,则可以简单地使用setCenter方法在屏幕上移动图像。

UIImage *headImage = [UIImage imageNamed:@"head"];
UIImageView *headView = [[UIImageView alloc] initWithImage:headImage];
[headView setCenter:CGPointMake(100, 100)]; // x, y
[self.view addSubview:headView];

暂无
暂无

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

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