【发布时间】:2012-12-26 16:37:24
【问题描述】:
我有 UIImageView,我在其中显示 50x100 图像。
我只想显示 50x50 图像的一部分(顶部)?
我该怎么做?
【问题讨论】:
-
这不是重复的,因为他的要求略有不同,但我认为它可能对您有所帮助:stackoverflow.com/questions/14042260/…
标签: iphone objective-c ios uiimageview uiimage
我有 UIImageView,我在其中显示 50x100 图像。
我只想显示 50x50 图像的一部分(顶部)?
我该怎么做?
【问题讨论】:
标签: iphone objective-c ios uiimageview uiimage
在UIImageView中移动大图的非常简单的方法如下。
让我们有一个大小为 (100, 400) 的图像,它代表某张图片的 4 种状态。我们想在大小为 (100, 100) 的正方形 UIImageView 中显示第二张 offsetY = 100 的图片。 解决办法是:
UIImageView *iView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
CGRect contentFrame = CGRectMake(0, 0.25, 1, 0.25);
iView.layer.contentsRect = contentFrame;
iView.image = [UIImage imageNamed:@"NAME"];
这里 contentFrame 是相对于真实 UIImage 大小的标准化框架。 所以,“0”意味着我们从左边框开始图像的可见部分, “0.25”意味着我们有垂直偏移100, “1”表示我们要显示图像的全宽, 最后,“0.25”表示我们只想显示图像高度的 1/4。
因此,在局部图像坐标中,我们显示以下帧
CGRect visibleAbsoluteFrame = CGRectMake(0*100, 0.25*400, 1*100, 0.25*400)
or CGRectMake(0, 100, 100, 100);
【讨论】:
您可以使用CGImageCreateWithImageInRect 裁剪图像,这是在 CGImageRef 上工作的 Quartz 原语,因此您会得到类似的东西:
CGImageRef imageRef = CGImageCreateWithImageInRect(originalImage.CGImage, cropRect);
UIImage* outImage = [UIImage imageWithCGImage:imageRef scale:originalImage.scale orientation:originalImage.imageOrientation]];
CGImageRelease(imageRef);
在计算cropRect时,请记住它应该以像素而不是点为单位给出,即:
float scale = originalImage.scale;
CGRect cropRect = CGRectMake(0, 0,
originalImage.size.width * scale, originalImage.size.height * 0.5 * scale);
0.5 因素说明您只想要上半部分。
如果您不想使用低级别,可以将图像添加到UIView 作为背景颜色,并使用clipToBounds CALayer 属性进行剪切:
myView.backgroundColor = [UIColor colorWithBackgroundPattern:myImage];
myView.layer.clipToBounds = YES;
另外,相应地设置myView 边界。
【讨论】:
我可能会为您提供解决方案。看看这是否有效。在 Interface Builder 中有一个关于图像内容填充属性的选项。您可以将其设置为top-left。按照界面生成器中的图像 -
在此之后将UIImageView 的大小设置为 50x50,并选中“clip-subviews”...
【讨论】: