Elie Teyssedou
Elie Teyssedou

Reputation: 779

Capture UIView in RubyMotion

I want to capture an UIView as an UIImage. I've tried many things, but I always get this kind of error :

<Error>: CGContextSaveGState: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.

Here is my captureView method :

  def captureView
    rect = view.bounds
    UIGraphicsBeginImageContext(rect.size)
    context = UIGraphicsGetCurrentContext
    view.layer(renderInContext:context)
    img = UIGraphicsGetImageFromCurrentImageContext
    UIGraphicsEndImageContext
    img
  end

What am I doing wrong ? Is there another way to capture images ?

Thanks.

Upvotes: 1

Views: 65

Answers (2)

colinta
colinta

Reputation: 3659

I suspect, @elie-teyssedou, that the thread you're running this code on has something to do with it.

I've seen this error when taking "snapshot specs" (FBSnapshotSpec), which I'm pretty sure are not running on the main thread. I haven't tested the theory, because the code actually works despite the error messages.

Other than that, the code you're using looks fine, so I suspect it's something going on with the environment you're running the code it.

Upvotes: 1

David Larrabee
David Larrabee

Reputation: 384

this is what I use

  def self.convert_view_to_image(view)
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, true, 0.0)
    view.layer.renderInContext(UIGraphicsGetCurrentContext())
    image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    image
  end

Upvotes: 0

Related Questions