在Swift中将UIView转换为.png
如何将UIView转换为图像。 我发现这将uiview转换为.png图像,但我不熟悉Objective-C。 我把这个翻译成了Swift,但是效果并不好。 有什么帮助吗?
UIGraphicsBeginImageContext(myView.frame.size); [myView.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); NSData *data=UIImagePNGRepresentation(viewImage); NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *strPath = [documentsDirectory stringByAppendingPathComponent:@"myimage.png"]; [data writeToFile:strPath atomically:YES];
尝试这个:
UIGraphicsBeginImageContextWithOptions(myView.layer.frame.size, false, scale) myView.layer.renderInContext(UIGraphicsGetCurrentContext()!) let viewImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() let data = UIImagePNGRepresentation(viewImage) let documentsDir = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String let writePath = documentsDir.stringByAppendingPathComponent("myimage.png") data.writeToFile(writePath, atomically:true)