我正在构建一个图像管理器类来处理UIImages的大小调整,裁剪等问题。我正在使用CGContext,因为它的速度可与UIGraphicsContext相媲美,其中JPEG来自http://nshipster.com/image-resizing/所见的基准。
这是我的经理班:
func resizeImage(exportedWidth width: Int, exportedHeight height: Int, originalImage image: UIImage) -> UIImage? {
let cgImage = image.CGImage
let width = width
let height = height
let bitsPerComponent = CGImageGetBitsPerComponent(cgImage)
let bytesPerRow = CGImageGetBytesPerRow(cgImage)
let colorSpace = CGImageGetColorSpace(cgImage)
let bitmapInfo = CGImageGetBitmapInfo(cgImage)
let context = CGBitmapContextCreate(nil, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo.rawValue)
CGContextSetInterpolationQuality(context, .High)
CGContextDrawImage(context, CGRect(origin: CGPointZero, size: CGSize(width: CGFloat(width), height: CGFloat(height))), cgImage)
let scaledImage = CGBitmapContextCreateImage(context).flatMap { UIImage(CGImage: $0) }
return scaledImage
}
没有什么真的太疯狂,但是当我将它添加到子类UITextView时我遇到了麻烦。我已经尝试将图像大小加倍然后用UIImageView压缩它无济于事。此代码正确显示正确的大小,但看起来像我的iPhone SE上的图像像素与屏幕像素比为1:1而不是理想的2:1视网膜屏幕。
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
let textViewWidth: CGFloat = self.view.frame.size.width - 130
let percentResize = textViewWidth / pickedImage.size.width
let toBeExportedHeight = pickedImage.size.height * percentResize
let resizedImage = ImageManipulationManager.sharedInstance.resizeImage(exportedWidth: Int(textViewWidth),exportedHeight: Int(toBeExportedHeight), originalImage: pickedImage)
let attachment = NSTextAttachment()
attachment.image = resizedImage
let attString = NSAttributedString(attachment: attachment)
textView.textStorage.insertAttributedString(attString, atIndex: textView.selectedRange.location)
textInputbar.layoutIfNeeded()
textView.becomeFirstResponder()
print(textView.text.characters.count)
}
dismissViewControllerAnimated(true, completion: nil)
}
答案 0 :(得分:0)
双分辨率屏幕的图像需要是双分辨率的。这意味着它应该是您想要的实际大小的两倍宽和两倍高,当您从CGImage派生它时,UIImage附加scale
2。