0
我正在構建一個圖像管理器類來處理UIImages的大小調整,裁剪等。我使用的是CGContext,因爲它的速度可以與來自http://nshipster.com/image-resizing/的基準的JPEG格式的UIGraphicsContext相媲美。使用CGContext調整UIImage的大小使得我的圖像柔軟,像素密度錯誤
這是我的經理類:
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壓縮它無濟於事。此代碼已正確顯示正確的大小,但看起來好像圖像像素與屏幕像素比例爲1:1,而不是我iPhone SE上視網膜屏幕的理想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)
}
我到底在哪裏將刻度設置爲兩倍大小。我嘗試將bitmapcontext的大小設置爲實際圖像邊界的一半大小的兩倍。然而,最終發生的情況是渲染尺寸相同,額外的空間爲黑色。 – ggworean
正如我在我的回答中所說的那樣,當你從CGImage派生UIImage的時候就這樣做了。 – matt
那麼代碼如何?我不知道我需要改變什麼屬性。我意識到這是規模,但我希望這對我有幫助。 – ggworean