【发布时间】:2011-11-18 09:20:23
【问题描述】:
如果我像这样实例化 UIImage:
UIImage *image = [[UIImage alloc] init];
对象已创建,但不包含任何图像。
如何检查我的对象是否包含图像?
【问题讨论】:
如果我像这样实例化 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 中检查 cgImage 或 ciImage
public extension UIImage {
public var hasContent: Bool {
return cgImage != nil || ciImage != nil
}
}
CGImage:如果 UIImage 对象是使用 CIImage 对象初始化的, 该属性的值为NULL。
CIImage:如果 UIImage 对象是使用 CGImageRef 初始化的,则 该属性的值为零。
【讨论】:
检查 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。如果两者都为零,则表示没有图像。 Give方法的使用示例:
if (![self containsImage:imageview.image]) {
[self setImageWithYourMethod];
}
希望对某人有所帮助。
【讨论】: