ios UIImage,检查是否包含图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8180177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 15:27:31  来源:igfitidea点击:

UIImage, check if contain image

iosuiimage

提问by Jonathan

If I instantiate a UIImage like this :

如果我像这样实例化 UIImage :

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

The object is created but it doesn't contain any image.

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

How I can check if my object contains an image or not?

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

回答by Kreiri

You can check if it has any image data.

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

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

CGImageRef cgref = [image CGImage];
CIImage *cim = [image CIImage];

if (cim == nil && cgref == NULL)
{
    NSLog(@"no underlying data");
}
[image release];

Swift Version

迅捷版

let image = UIImage()

let cgref = image.cgImage
let cim = image.ciImage

if cim == nil && cgref == nil {
    print("no underlying data")
}

回答by onmyway133

Check for cgImageor ciImage, in Swift 3

在 Swift 3 中检查cgImageciImage

public extension UIImage {

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

CGImage: If the UIImage object was initialized using a CIImage object, the value of the property is NULL.

CIImage: If the UIImage object was initialized using a CGImageRef, the value of the property is nil.

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

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

回答by mgyky

This is updated version of @Kreiri, I put in a method and fixed logic error:

这是@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;
}

An UIImage could only based on CGImageRef or CIImage. If both is nil means there is no image. Example use of giving method:

UIImage 只能基于 CGImageRef 或 CIImage。如果两者都是 nil 表示没有图像。给予方法的使用示例:

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

hope it will help someone.

希望它会帮助某人。

回答by Mahesh Aswathanarayana

Check with CGImageRef with itself wheather it contains null value means UIImage object not contains image.......

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