Take a Snapshot of a UIView

Sometimes, you may need generate an image of a view to share or somethings you need a picture.

So, here is the way to do this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var frame // the frame of the Snapshot.
var view // the view you want to take a snapshot.

if UIScreen.mainScreen().scale > 1 {
UIGraphicsBeginImageContextWithOptions(frame.size, false, UIScreen.mainScreen().scale)
} else {
UIGraphicsBeginImageContext(frame.size)
}

let context = UIGraphicsGetCurrentContext()

CGContextTranslateCTM(context, -frame.minX, -frame.minY)

view.layer.renderInContext(context!)

let image = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext()

imageView.image = image

Things has been done.

Proudly powered by Hexo and Theme by Hacker
© 2021 KK