2012-12-05 34 views
19

我想创建一个框,弹出我的xcode应用程序,只显示该大小的图像。我有以下几种:创建一个UIImageView,裁剪一个图像,并在50x和200y显示100w 100h

UIImageView *newView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"beach.jpg"]]; 

但是,这会创建完整大小的图像,并只显示它。我怎么会只显示100瓦100小时50和200下?我会用CGRect吗?

另外,我可以让它点击它导致它消失吗?

编辑#1 我不想调整图像大小 - 宁愿只拉100平方像素,并将它们放在一个框架中。

+0

您需要添加UITapGestureRecognizer上的UIImageView为攻。 – nhahtdh

+0

编辑:然后设置边界而不是框架。您不需要contentMode,但需要将clipsToBounds设置为YES。 – nhahtdh

回答

67

请尝试使用下面的代码。下面的代码

MyImageview.contentMode = UIViewContentModeScaleAspectFill; 
MyImageview.clipsToBounds = YES; 
+0

是的......这2个需要与框架一起设置。 – nhahtdh

+0

thx P,这是调整图像大小 - 任何方式来获得原始大小? – timpone

+0

你试过MyImageview.contentMode = UIViewContentModeTopLeft; –

15

您可以用剪切图像:

CGRect cropRegion = CGRectMake(50, 200, 100, 100); 
UIImage *image = [UIImage imageNamed:@"beach.jpg"]; 
CGImageRef subImage = CGImageCreateWithImageInRect(image.CGImage, cropRegion); 
UIImage *croppedImage = [UIImage imageWithCGImage:subImage]; 
UIImageView *newView = [[UIImageView alloc] initWithImage:croppedImage]; 
+0

这很好。很高兴看到一个解决方案,不需要创建全新的上下文和东西只是一点点的收获。 – weienw

8

您也可以实现通过检查剪辑子视图在故事板选项的裁剪效果。

enter image description here

+0

不,它不工作@Yuchenzhong –

+0

@Mansuu ....它应该工作。如果没有,请尝试在代码https://stackoverflow.com/a/13715487/1035008中执行此操作,该操作应该等同于这两个设置。 –