How do I take a screenshot of a single view object instead of the entire screen?

So I have a UIImageView with some text overlayed on the top and bottom. I want to get a screenshot so I have a new image with the text overlayed on it. This is the code I was working with but I am unable to take a screenshot of the my UIImageView object properly.

func generateImage() -> UIImage
{
    // Render view to an image
    UIGraphicsBeginImageContext(self.view.frame.size)
    view.drawViewHierarchyInRect(self.imageView.frame,
        afterScreenUpdates: true)
    let memeImage: UIImage =
    UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return memeImage
}

Alternatively, I have also tried the code below, though the image saved is the right size/area of the screen, it ends up with blurry version of what I took a screenshot of:

UIGraphicsBeginImageContext(self.imageView.frame.size)
    let context = UIGraphicsGetCurrentContext()

imageView.layer.renderInContext(context!) // tried drawInContext but it didn't work at all
let memeImage = UIGraphicsGetImageFromCurrentImageContext()

UIGraphicsEndImageContext()
return memeImage

Answers


First, using UIGraphicsBeginImageContextWithOptions will allow you to adjust the scale factor to suit your screen size. Second, passing in the view you want to capture will ensure that you are working with the correct view/subviews.

func generateImage(currentView: UIView) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(currentView.frame.size, true, 0.0)
        currentView.layer.renderInContext(UIGraphicsGetCurrentContext()!)
        let memeImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        //UIImageWriteToSavedPhotosAlbum(memeImage, nil, nil, nil)

        return memeImage
    }

Need Your Help

Get entire URL, including query string and anchor

php

Is there a way to get the entire URL used to request the current page, including the anchor (the text after the # - I may be using the wrong word), in included pages?

.NET framework is copied to 'compiler/CLR' and 'GAC?

.net assemblies gac

The book of CLR via C# has this line at page 76.