UIImage,检查是否包含图像



如果我这样实例化一个UIImage:

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

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

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

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

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")
}

检查Swift 3中的cgImageciImage

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

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

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

检查CGImageRef本身是否包含空值表示UIImage对象不包含图像.......

这是@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。如果两者都为nil,则表示没有图像。给出方法的例子:

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

希望对大家有所帮助。

最新更新