如何显示在UIImage只是图像的一部分?

我有我在显示50×100图像的UIImageView

我只想显示图像的一部分50×50(顶部)?

我怎样才能做到这一点?

我可能会为你解决。 看看这是否有效。 在界面生成器中有一个关于图像内容填充属性的选项。 您可以将其设置为top-left 。 按照界面生成器中的图像 –

在这里输入图像说明

之后,将“clip-subviews”选中,将UIImageView的大小设置为50×50。

您可以使用CGImageCreateWithImageInRect (它是CGImageCreateWithImageInRect上的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界限。

UIImageView中移动大图像的非常简单的方法如下。

让我们把尺寸(100,400)的图像代表一个图像的四个状态。 我们要在大小为(100,100)的方形UIImageView中显示具有偏移量Y = 100的第二张图片。 解决scheme是:

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