以下是代码:
@interface InterfaceController()
@property (nonatomic, weak) IBOutlet WKInterfaceImage *qrImage;
@property (nonatomic, weak) IBOutlet WKInterfaceLabel *label;
@end
@implementation InterfaceController
- (void)awakeWithContext:(id)context {
[super awakeWithContext:context];
[self.label setText: @"Welcome"];
UIImage *image = [InterfaceController generateQRCodeWithString:@"Welcome"];
[self.qrImage setImage:image];
}
- (void)willActivate {
[super willActivate];
}
- (void)didDeactivate {
[super didDeactivate];
}
+ (UIImage *)generateQRCodeWithString:(NSString *)string {
NSData *stringData = [string dataUsingEncoding:NSUTF8StringEncoding];
CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
[filter setValue:stringData forKey:@"inputMessage"];
[filter setValue:@"M" forKey:@"inputCorrectionLevel"];
CIImage *input = filter.outputImage;
CGAffineTransform transform = CGAffineTransformMakeScale(10.0f, 10.0f);
CIImage *output = [input imageByApplyingTransform: transform];
return [UIImage imageWithCIImage:output];
}
@end
我正在尝试从某些特定文本生成QR码并在watch界面中显示它.问题是从不显示generateQRCodeWithString:生成的UIImage.但是,如果我从WatchKit Extension包中加载带有[UIImage imageNamed:@“XXX.png”]的图像,则会正确显示.
我不确定发生了什么.我错过了什么?提前致谢.
更新:回应msk,是的,我很确定.我试图NSLog图像,它给出< UIImage:0x7fc261d276e0>,{230,230}
最佳答案 从generateQRCodeWithString:返回的图像不是“真实”图像(简短)并且尚未完全渲染出来.将CIImage视为图像应该是什么样子而不是实际像素的概念.
替换generateQRCodeWithString中的返回行:如下所示:
CGImageRef cgOutput = [[CIContext contextWithOptions:nil]
createCGImage:output fromRect:output.extent];
return [UIImage imageWithCGImage:cgOutput];
这将使QR码呈现为CGImage,将其转换为像素,然后转换为UIImage.
创建CIContext是相对昂贵的,如果你生成了大量的QR代码,那么上下文应该是静态的,或者初始化一次.但对于一次性,它应该没问题.