0

I would like to make partial screenshot in my project. However, I tried the output screenshot is not good that I want to be.
Here is my code.

let size = CGSize(width: 398, height: 300)

    UIGraphicsBeginImageContextWithOptions(size, false, 0);

    view.layer.render(in: UIGraphicsGetCurrentContext()!)

    var sourceImage = UIGraphicsGetImageFromCurrentImageContext()

    sourceImage?.draw(at: CGPoint(x: 0, y: 0))

    var cropimage = UIGraphicsGetImageFromCurrentImageContext()


    UIGraphicsEndImageContext()
    UIImageWriteToSavedPhotosAlbum(cropimage!,nil,nil,nil)

enter image description here


I would like to save only white View. If I set width and height, the output image is small and does not get completely.
Anyone help me please?

May Phyu
  • 895
  • 3
  • 23
  • 47
  • I believe you have to set the rect of the graphic context. Another approach would be to take a full screenshot and then crop the image. Give Google a try! – LinusGeffarth Mar 28 '17 at 10:31
  • 1
    Maybe the answer in [here](http://stackoverflow.com/questions/2214957/how-do-i-take-a-screen-shot-of-a-uiview) can help you, just take the screenshot of the specific subview, don't need crop – Tj3n Mar 28 '17 at 10:31
  • Thanks for your feedback and advices @Tj3n. – May Phyu Mar 28 '17 at 11:29

1 Answers1

1

extend UIView and capture an image of that white view

// Untested
import UIKit

extension UIView {

  func capture() -> UIImage {

    UIGraphicsBeginImageContextWithOptions(self.frame.size, self.opaque, UIScreen.mainScreen().scale)
    self.layer.renderInContext(UIGraphicsGetCurrentContext()!)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return image
  }

}

usage:

let whiteImage = myWhiteView.capture()
Damo
  • 12,840
  • 3
  • 51
  • 62
  • Bro I write this to save image in photoGallery. UIImageWriteToSavedPhotosAlbum(cropimage!,nil,nil,nil) But I see the image in Gallery, the white part is small and the black screen is appear at the right side. Why this is happen bro? Thank you very much for your help bro. – May Phyu Mar 28 '17 at 11:28
  • make sure that the view you are capturing is only the white view and not it's superview... – Damo Mar 28 '17 at 11:42
  • Hello @Damo, I made UIView outlet to white view. Then, I write your code. I declare var whiteViewImage: UIImage! and declare this whiteViewImage = qrView.capture() within viewDidLoad(). I write photo save function when user clicks on button. I didn't define the width of white View. I only set the height of White View. – May Phyu Mar 29 '17 at 02:55
  • share the actual image it creates here (you could send it to yourself via email). i.e. let's look at it outside of the gallery. – Damo Mar 29 '17 at 09:06
  • 1
    bro @Damo, I changed this UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, 0) . It works!. – May Phyu Mar 29 '17 at 09:59