UIGraphicsBeginImageContext doesn't return retina image - ios

I want to capture current screen in an image. I'm doing this:
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.isOpaque, UIScreen.main.scale)
self.view.drawHierarchy(in: self.view.bounds, afterScreenUpdates: false)
let snapshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
Problem is the scale parameter. If I understand correctly 0.0 represents non-retina, 2.0 represents retina and 3.0 represents retina for 6 Plus and 7 Plus. No matter what I input into the scale parameter, the output is always image with 375x667 resolution. I also tried different approach:
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.isOpaque, UIScreen.main.scale)
self.view.layer.render(in: UIGraphicsGetCurrentContext()!)
let snapshot: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
Again, same scenario. I'm even using
UIScreen.main.scale
Which in fact returns value 2.0. What am I doing wrong? How do I get a higher resolution image?

This code will do the trick
let contextSize = CGSize(width: self.view.bounds.size.width * UIScreen.main.scale, height: self.view.bounds.size.height * UIScreen.main.scale)
UIGraphicsBeginImageContextWithOptions(contextSize, self.view.isOpaque, UIScreen.main.scale)
self.view.layer.render(in: UIGraphicsGetCurrentContext()!)
let snapshot: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
CGContext don't care about scale, it care about size only.
EDIT
You may want to use the newer API available in iOS 10 and later
let renderer = UIGraphicsImageRenderer(bounds: self.view.bounds)
let snapshot = renderer.image(actions: { context in
self.view.layer.render(in: context.cgContext)
})

snapshot is a UIImage which has two properties, size and scale; much like the screen. To determine the actual size in pixels of the image you must multiply the the size by the scale. I think your issue is that you're assuming the size property is pixels not points.
size
The logical dimensions of the image, measured in points.
You can test this in a very definitive way by creating a JPG using UIImageJPEGRepresentation and saving it to disk to inspect using image tools you're familiar with.

Related

Quality get reduced when convert imageview to image

In photo editor screen , I have imageview and it has background image and on top of imageview I add elements like text (label), stickers(images) etc. , Now for the final image containing all elements added on imageview , I am getting image from below code
clipRect is rect for background image inside imageview, image is aspectfit in imageview
Below is code inside UIView extension which has function to generate image out of view.
self == uiview
let op_format = UIGraphicsImageRendererFormat()
op_format.scale = 1.0
let renderer = UIGraphicsImageRenderer(bounds: CGRect(origin: clipRect!.origin, size: outputSize), format: op_format)
let originalBound = self.bounds
self.bounds = CGRect(origin: clipRect!.origin, size: clipRect!.size)
var finalImage = renderer.image { ctx in
self.drawHierarchy(in: CGRect(origin: self.bounds.origin, size: outputSize), afterScreenUpdates: true)
}
self.bounds = CGRect(origin: originalBound.origin, size: originalBound.size)
Issue here is quality of final image quality is very poor as compared to original background image.
Don't set the scale of your UIGraphicsImageRendererFormat to 1. That forces the output image to #1x (non-retina). For most (all?) iOS devices, that will cause a 2X or 3X loss of resolution. Leave the scale value of the UIGraphicsImageRendererFormat at the default value.
you can take screenshot as well
// Convert a uiview to uiimage
func captureView() -> UIImage {
// Gradually increase the number for high resolution.
let scale = 1.0
UIGraphicsBeginImageContextWithOptions(bounds.size, opaque, scale)
layer.renderInContext(UIGraphicsGetCurrentContext()!)
let image:UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}

Resizing UIImage to fit table cell ImageView

I have images of the size 176 points by 176 points. I am trying to resize them so that they fit into a tableViewCell's ImageView. There are a few problems that I am coming across.
Problems
I don't know what size the image view in the tableViewCell actually is.
If I simply add the image without resizing it, it is so sharp that it looses detail:
If I use this extension on UIImage (below), then the transparent parts of the UIImage turn to black, not what I want:
extension UIImage {
func resizeImageWithBounds(bounds: CGSize) -> UIImage {
let horizontalRatio = bounds.width/size.width
let verticalRatio = bounds.height/size.height
let ratio = max(horizontalRatio, verticalRatio)
let newSize = CGSize(width: size.width * ratio, height: size.height * ratio)
UIGraphicsBeginImageContextWithOptions(newSize, true, 0)
draw(in: CGRect(origin: CGPoint.zero, size: newSize))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
I am looking for information on how big the UIImageView is and how to best resize an image into it. I really don't want to create another set of assets (I have a lot of images), and I don't think I should have to.
Try changing the contentMode of the cell.
cell.imageView?.contentMode = .scaleAspectFit
Or, if that doesn't work, here's how to fix the issues of your resized images turning black:
UIGraphicsBeginImageContextWithOptions(newSize, false, 0) // <-- changed opaque setting from true to false

Pasteboard UIImage not using scale

I am building a custom keyboard and am having trouble adding an image to the pasteboard and maintaining the appropriate scale and resolution with in the pasted image. Let me start with a screenshot of the keyboard to illustrate my trouble:
So the picture of the face in the top left of the keyboard is just a UIButton with the original photo set to the background. When the button is pressed the image is resized with the following function:
func imageResize(image:UIImage, size:CGSize)-> UIImage {
let scale = UIScreen.mainScreen().scale
UIGraphicsBeginImageContextWithOptions(size, false, scale)
var context = UIGraphicsGetCurrentContext()
CGContextSetInterpolationQuality(context, kCGInterpolationHigh)
image.drawInRect(CGRect(origin: CGPointZero, size: size))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage
}
This function creates a UIImage the same size as the UIButton with the appropriate scale to reflect the device's screen resolution. To verify that the function is correct, I added an UIImageView filled with the scaled image. The scaled image is the image that looks misplaced near the center of the keyboard. I added the UIImageView with this function:
func addImageToBottomRight(image: UIImage) {
var tempImgView = UIImageView(image: image)
self.view.addSubview(tempImgView)
tempImgView.frame.offset(dx: 100.0, dy: 50.0)
}
I have tried a few different methods for adding the image to the pasteboard, but all seem to ignore the scale of the image and display it twice as large as opposed to displaying it at a higher resolution:
let pb = UIPasteboard.generalPasteboard()!
var pngType = UIPasteboardTypeListImage[0] as! String
var jpegType = UIPasteboardTypeListImage[2] as! String
pb.image = image
pb.setData(UIImagePNGRepresentation(image), forPasteboardType: pngType)
pb.setData(UIImageJPEGRepresentation(image, 1.0), forPasteboardType: jpegType)
All three of these methods do not work correctly and produce the same result as illustrated in the screenshot. Does anyone have any suggestions of other methods? To further clarify my goal, I would like the image in the message text box to look identical to both UIImages in the keyboard in terms of size and resolution.
Here are a few properties of the UIImage before and resize in case anyone is curious:
Starting Image Size is (750.0, 750.0)
Size to scale to is: (78.0, 78.0))
Initial Scale: 1.0
Resized Image Size is (78.0, 78.0)
Resized Image Scale: 2.0
I know this is an old post, but thought I share the work around I found for this specific case of copying images and pasting to messaging apps.The thing is, when you send a picture with such apps like iMessages, whatsapp, messenger, etc, the way they display the image is so that it aspect fits to some certain horizontal width (lets say around 260 pts for this demo).
As you can see from the diagram below, if you send 150x150 image #1x resolution in imessage, it will be stretched and displayed in the required 260 width box, making the image grainy.
But if you add an empty margin of width 185 to both the left and right sides of the image, you will end up with an image of size 520x150. Now if you send that sized image in imessage, it will have to fit it in a 260 width box, ending up cramming a 520x150 image in a 260x75 box, in a way giving you a 75x75 image at #2x resolution.
You can add a clear color margin to a UIImage with a code like this
extension UIImage {
func addMargin(withInsets inset: UIEdgeInsets) -> UIImage? {
let finalSize = CGSize(width: size.width + inset.left + inset.right, height: size.height + inset.top + inset.bottom)
let finalRect = CGRect(origin: CGPoint(x: 0, y: 0), size: finalSize)
UIGraphicsBeginImageContextWithOptions(finalSize, false, scale)
UIColor.clear.setFill()
UIGraphicsGetCurrentContext()?.fill(finalRect)
let pictureOrigin = CGPoint(x: inset.left, y: inset.top)
let pictureRect = CGRect(origin: pictureOrigin, size: size)
draw(in: pictureRect)
let finalImage = UIGraphicsGetImageFromCurrentImageContext()
defer { UIGraphicsEndImageContext() }
return finalImage
}
}

Issue while trying to save an image to the camera roll SWIFT

Encountered a strange issue while trying to save a view.
The picture saved crops out the image.
here is the code :
let scale = UIScreen.mainScreen().scale
let size:CGSize = CGSize(width: CGFloat(self.customView!.frame.size.width), height: CGFloat(self.customView!.frame.size.height))
UIGraphicsBeginImageContextWithOptions( size, false, scale);
self.customView!.layer.renderInContext(UIGraphicsGetCurrentContext())
let screenshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIImageWriteToSavedPhotosAlbum(screenshot, nil, nil, nil)
Please help!
thanks in advance
The camera roll has an auto zoom since the height is a bit smaller than the screen.

Retina screenshot (Swift)

I am trying to take a screenshot of the UIView using the code below but it is creating a non-retina screenshot at half of the sizes of the actual device screen size.
Where am I going wrong?
Also view.frame.size is returning half of the actual values.
let scale = UIScreen.mainScreen().scale
UIGraphicsBeginImageContextWithOptions(view.frame.size, false, scale)
view.layer.renderInContext(UIGraphicsGetCurrentContext())
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIImageWriteToSavedPhotosAlbum(newImage, nil, nil, nil)
Thanks

Resources