繁体   English   中英

如何设置UIImage边界?

[英]How do I set UIImage bounds?

我在为UIImageView设置图像的正确位置时遇到麻烦,我将其作为子视图添加到UIButton 我首先创建按钮并添加一些子层:

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];

然后,我使用两种方法设置图像。 第一个(如果未保存任何图像,则使用该图像)使用图像资源,该图像资源已缩放为正确的大小,并且是应用程序捆绑包的一部分。 我用以下代码设置:

UIImageView *v = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"profile.png"]];
[v setBounds:CGRectInset(button.bounds, 8, 8)];
[button addSubview:v];

问题出在我使用通过相机拍摄并保存到文件系统的图像时。 我使用以下代码将此设置为背景:

//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];

屏幕上的输出现在显示图像路径与应偏移的位置:

例

我究竟做错了什么? 如何正确缩放/适合其父视图中的图像? 我尝试仅设置按钮图像,但是什么也没出现(也许图像在子层后面?)。

使用setFrame方法设置imageview的框架而不是bounds

[v setFrame:CGRectInset(button.bounds, 8, 8)];

因此,代码变成

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.

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