0

I'm trying to use cocos2d to take a screenshot of the current scene. Working off of this answer to a previous question, I translated it over to Swift, and got this:

func takeScreenshot() -> UIImage {
    CCDirector.sharedDirector().nextDeltaTimeZero = true

    let viewSize: CGSize = CCDirector.sharedDirector().viewSize()
    let renderTexture: CCRenderTexture = CCRenderTexture.renderTextureWithWidth(viewSize.width, height: viewSize.height)

    renderTexture.begin()
    CCDirector.sharedDirector().runningScene.visit()
    renderTexture.end()

    return renderTexture.getUIImage()
}

However, I get a compiler error on:

let renderTexture: CCRenderTexture = CCRenderTexture.renderTextureWithWidth(viewSize.width, height: viewSize.height)

It says "cannot invoke 'renderTextureWithWidth' with an argument list of type '(CGFloat, height: CGFloat)'".

I checked the CCRenderTexture.h file, and it says:

+(instancetype)renderTextureWithWidth:(int)w height:(int)h;

I tried type casting the viewSize.width and the viewSize.height to Int, but it still gave the same "cannot invoke" error again.

Anyone know why this is the case and how it can be fixed?

Community
  • 1
  • 1
Zachary Espiritu
  • 937
  • 7
  • 23

1 Answers1

1

These type conversions can be tricky. But if you use the default Swift constructor CCRenderTexture(width: Int32, height: Int32) and not the objective-c factory method (the one you tried to use) auto completion will help you out. You need to cast to Int32 .

Pontus Armini
  • 348
  • 4
  • 10
  • Simple and straightforward solution. Thanks so much for the help - it works like a charm. – Zachary Espiritu Jul 19 '15 at 18:47
  • Glad it helped! Perhaps I should have mentioned that whenever you see an objective-c `int`, you can/should use the Swift type `CInt` — which simply is a type alias of `Int32`, but perhaps easier to remember. So, you could have used that here. See the docs for more info: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithCAPIs.html#//apple_ref/doc/uid/TP40014216-CH8-XID_11 – Pontus Armini Jul 19 '15 at 20:07