显示UIImageview的顶部部分

时间:2013-04-23 18:19:03

标签: iphone ios objective-c xcode uiimage

我正在尝试显示UIImage的顶部。

我知道我可以使用以下代码并显示中间部分。我只想弄清楚如何对顶部做同样的事情:

imageView.contentMode = UIViewContentModeScaleAspectFill;
imageView.clipsToBounds = YES;

我从服务器获取的UIImage大小不一定相同,所以我不能使用UIViewContentModeTopLeft。我想要一种缩放图像并显示顶部的方法。

感谢。

2 个答案:

答案 0 :(得分:2)

您希望显示图像的任意矩形,因此最简单的方法是将imageView放在常规视图中。您可以设置图像视图的框架以显示所需的位,并设置封闭视图以进行裁剪。

e.g。你有一个1000 x 1000像素的图像,你想显示矩形200,200到400,400

UIImageView* imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"SomeImage"]];
imageView.frame = CGRectMake( -200, -200, 1000, 1000);
UIView* enclosingView = [[UIView alloc] initWithFrame:CGRectMake( 0, 0, 200, 200);
enclosingView.clipsToBounds = YES;
[enclosingView addSubview: imageView];

在这种情况下,内容模式并不重要,因为您要设置图像视图的尺寸以匹配图像。

答案 1 :(得分:0)

一种方法是在原始图片上调用CGImageCreateWithImageInRect以创建仅包含顶部的新图像。

类似的东西:

CGImageRef newImageRef = CGImageCreateWithImageInRect( oldImage.CGImage, CGRectMake(0,0,50,50) );
UIImage *newImage = [UIImage imageWithCGImage:newImageRef];
CGImageRelease( newImageRef );

然后显示newImage而不是oldImage。

相关问题