【问题标题】:UIImage, check if contain imageUIImage,检查是否包含图像
【发布时间】:2011-11-18 09:20:23
【问题描述】:

如果我像这样实例化 UIImage:

UIImage *image = [[UIImage alloc] init];

对象已创建,但不包含任何图像。

如何检查我的对象是否包含图像?

【问题讨论】:

    标签: ios uiimage


    【解决方案1】:

    您可以检查它是否有任何图像数据。

    UIImage* image = [[UIImage alloc] init];
    
    CGImageRef cgref = [image CGImage];
    CIImage *cim = [image CIImage];
    
    if (cim == nil && cgref == NULL)
    {
        NSLog(@"no underlying data");
    }
    [image release];
    

    斯威夫特版

    let image = UIImage()
    
    let cgref = image.cgImage
    let cim = image.ciImage
    
    if cim == nil && cgref == nil {
        print("no underlying data")
    }
    

    【讨论】:

    • 但是 [图像 CIImage];仅适用于 iOS 5。4.3 呢?
    【解决方案2】:

    在 Swift 3 中检查 cgImageciImage

    public extension UIImage {
    
      public var hasContent: Bool {
        return cgImage != nil || ciImage != nil
      }
    }
    

    CGImage:如果 UIImage 对象是使用 CIImage 对象初始化的, 该属性的值为NULL。

    CIImage:如果 UIImage 对象是使用 CGImageRef 初始化的,则 该属性的值为零。

    【讨论】:

    • 如果没有图像则崩溃...在展开 Optional 时意外发现 nil
    【解决方案3】:

    检查 CGImageRef 本身是否包含空值意味着 UIImage 对象不包含图像.......

    【讨论】:

      【解决方案4】:

      这是@Kreiri的更新版本,我输入了一个方法并修复了逻辑错误:

      - (BOOL)containsImage:(UIImage*)image {
          BOOL result = NO;
      
          CGImageRef cgref = [image CGImage];
          CIImage *cim = [image CIImage];
      
          if (cim != nil || cgref != NULL) { // contains image
              result = YES;
          }
      
          return result;
      }
      

      一个 UIImage 只能基于 CGImageRef 或 CIImage。如果两者都为零,则表示没有图像。 Give方法的使用示例:

      if (![self containsImage:imageview.image]) {
          [self setImageWithYourMethod];
      }
      

      希望对某人有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-02-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多