【问题标题】:Showing only a portion of the original image in a UIImageView在 UIImageView 中仅显示原始图像的一部分
【发布时间】:2012-11-27 05:53:52
【问题描述】:

如何在 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];

【问题讨论】:

    标签: objective-c ios uiimageview


    【解决方案1】:

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

    imageView.contentMode = UIViewContentModeCenter;
    imageView.clipsToBounds = YES;
    

    【讨论】:

    • 至少请阅读问题..这与设置内容模式无关
    • 立即尝试。写下你的评论
    • 现在你来了一个爆炸......谢谢哥们,非常感谢你现在你应该 +1.... 和接受
    【解决方案2】:

    试试这个:

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

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

    【讨论】:

    • 我遇到了这个问题,想知道,我可以显示图像的一部分,然后当我调整 imageview 的大小时,显示整个图像?
    • 谢谢,这比裁剪图像要容易得多。 Swift 4 代码:self.backgroundImageView.layer.contentsRect = CGRect(x: 0.25, y: 0.25, width: 0.5, height: 0.5)
    【解决方案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;
    }
    

    【讨论】:

      【解决方案4】:

      您尝试缩放图像,然后在 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;
      

      }

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-11-09
        • 1970-01-01
        • 1970-01-01
        • 2020-06-01
        • 2013-03-24
        • 1970-01-01
        • 2020-12-21
        • 2011-10-17
        相关资源
        最近更新 更多