3

如何在 UIImageView 中仅显示原始图像的一部分

这个问题可能很熟悉而且很老,但是再次问的原因是,我在那些答案的帮助下找不到可行的想法很多人说 set image.contentMode = UIViewContentModeCenter; (但不工作)

我几乎需要一个包含原始图像中心的矩形,我如何得到这个?

当我向我的应用程序显示静态图像并将 UIImageVie 的内容模式设置为 Aspect Fill 时,我确实做到了这一点。但这在我从 url 显示图像并使用 NSData 的情况下不可行

添加我的代码和图像

   NSString *weburl = @"http://topnews.in/files/Sachin-Tendulkar_15.jpg";
   UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 50, 108, 86)];
   NSURL *url = [NSURL URLWithString:weburl];
   NSData *data = [NSData dataWithContentsOfURL:url];
   imageView.image = [UIImage imageWithData:data];

   [self.view addSubview:imageView];

原始图像 当前输出 需要

4

4 回答 4

8

如果您添加了 UIImageView 表单 XIB,您可以在那里找到一个“模式”属性,然后您可以从那里查看和设置不同的模式(来自界面生成器)。或者通过编程方式,您可以设置不同的模式

imageView.contentMode = UIViewContentModeCenter;
imageView.clipsToBounds = YES;
于 2012-11-27T06:16:52.097 回答
5

试试这个:

self.imageView.layer.contentsRect = CGRectMake(0.25, 0.25, 0.5, 0.5);

self.imageView 将显示图像的中间部分。你可以自己计算 CGRect 所需的值 ​</p>

于 2012-11-27T09:57:58.767 回答
3

对于这种输出,您需要根据您的要求裁剪图像。

裁剪代码如下,可以使用。

-(UIImage *) CropImageFromTop:(UIImage *)image
{
    CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(0, 12, image.size.width, image.size.height - 12));
    UIImage *cropimage = [[[UIImage alloc] initWithCGImage:imageRef] autorelease];
    CGImageRelease(imageRef);
    return cropimage;
}
于 2012-11-27T05:59:00.507 回答
-1

您尝试缩放图像,然后在 UiImageView 中添加图像并将该图像设置为中心,然后它位于中心。比例图像的代码是

-(UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize{
   UIGraphicsBeginImageContext(newSize);
   [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
   UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();
   return newImage;

}

然后你设置该图像的中心并添加到图像视图中我希望这是工作

于 2012-11-27T06:29:23.873 回答