[英]How do I set UIImage bounds?
I am having some trouble setting the correct location of the image for a UIImageView
, which I am adding as a subview to a UIButton
. 我在为
UIImageView
设置图像的正确位置时遇到麻烦,我将其作为子视图添加到UIButton
。 I start by creating the button and adding some sublayers: 我首先创建按钮并添加一些子层:
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:bounds];
//add gradient background
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = button.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[UIColor colorWithRed:.5 green:.5 blue:.5 alpha:1.0].CGColor, (id)[[UIColor blackColor] CGColor], nil];
[button.layer insertSublayer:gradient atIndex:0];
//set green background
CALayer *layer = [CALayer layer];
layer.frame = CGRectInset(button.bounds, 5, 5);
layer.backgroundColor = [UIColor colorWithRed:.55 green:.8 blue:.5 alpha:1.0].CGColor;
[button.layer insertSublayer:layer above:gradient];
I then use two methods to set the image. 然后,我使用两种方法设置图像。 The first (which I use if no image is saved) uses an image resource that is scaled to be the right size, and is part of the app bundle.
第一个(如果未保存任何图像,则使用该图像)使用图像资源,该图像资源已缩放为正确的大小,并且是应用程序捆绑包的一部分。 I set this with the following code:
我用以下代码设置:
UIImageView *v = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"profile.png"]];
[v setBounds:CGRectInset(button.bounds, 8, 8)];
[button addSubview:v];
The trouble comes from when I use an image taken through the camera, and saved to the file system. 问题出在我使用通过相机拍摄并保存到文件系统的图像时。 I am setting this to the background using the following code:
我使用以下代码将此设置为背景:
//path is an NSString set the the documents location of the image.
UIImageView *v = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:path]];
[v setBounds:CGRectInset(button.bounds, 8, 8)];
[v setContentMode:UIViewContentModeScaleToFill];
[button addSubview:v];
The output to the screen now shows the image way offset from where it should be: 屏幕上的输出现在显示图像路径与应偏移的位置:
What am I doing wrong? 我究竟做错了什么? How do I correctly scale/fit the image in its parent view?
如何正确缩放/适合其父视图中的图像? I have tried simply setting the button image, but nothing appeared (perhaps the image was behind the sublayers?).
我尝试仅设置按钮图像,但是什么也没出现(也许图像在子层后面?)。
Use - setFrame
method to set the frame of imageview instead of bounds
使用
setFrame
方法设置imageview的框架而不是bounds
[v setFrame:CGRectInset(button.bounds, 8, 8)];
Thus the code become 因此,代码变成
UIImageView *v = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:path]];
[v setFrame:CGRectInset(button.bounds, 8, 8)];
[v setContentMode:UIViewContentModeScaleToFill];
[button addSubview:v];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.