UIImage,检查是否包含图像
如果我像这样实例化一个UIImage:
UIImage *image = [[UIImage alloc] init];
该对象已创build,但不包含任何图像。
我如何检查我的对象是否包含图像?
你可以检查它是否有任何图像数据。
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 3中检查cgImage
或ciImage
public extension UIImage { public var hasContent: Bool { return cgImage != nil || ciImage != nil } }
CGImage:如果使用CIImage对象初始化UIImage对象,则该属性的值为NULL。
CIImage:如果使用CGImageRef初始化UIImage对象,则该属性的值为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。 如果两者都是零意味着没有图像。 给出方法的例子使用:
if (![self containsImage:imageview.image]) { [self setImageWithYourMethod]; }
希望它能帮助别人。