Home > front end >  Swift: understanding pointers
Swift: understanding pointers

Time:02-08

I'm trying to create a CoreGraphics Context using the following MacOS Quartz API:

CGContext.init?(_ url: CFURL, 
                mediaBox: UnsafePointer<CGRect>?, 
                _ auxiliaryInfo: CFDictionary?)

, but I'm having trouble with the concept of pointers. I can initiate the context thus:

var mypointer: UnsafeMutablePointer<CGRect>!
mypointer.pointee = myCGRectangle
var writeContext = CGContext.init(outURL, mediaBox: mypointer, nil)

But it says that pointee is a get-only property. I've tried:

var mypointer: UnsafePointer<CGRect>! = UnsafePointer(myCGRectangle)

, based on this, but I get cannot convert CGRect to expected type, amongst other errors.

I have looked at several other questions here about pointers, but I can't find anything useful within them.

CodePudding user response:

Just pass a reference to your myCGRectangle variable, this will create the needed UnsafeMutablePointer:

var writeContext = CGContext(outURL, mediaBox: &myCGRectangle, nil)

Make sure the rectangle variable is declared as var, otherwise the & won't work.

More details can be found on this excellent Apple documentation page about passing pointers to functions that require ones.

CodePudding user response:

Typically you do not just create a variable of type UnsafeMutablePointer<CGRect> and pass it to the init(_:mediaBox:_:). You rather pass a rectangle for which PDF will be displayed, e.g.

var mediaBox = CGRect(x: 0, y: 0, width: 300, height: 500)
...
var writeContext = CGContext(outURL, mediaBox: &mediaBox, nil)

(even that is a simplification, as it creates a rectangle directly. Usually you have some rectangle of the view you want to display PDF in, so you will be passing that rectangle.)

You are also allowed to pass nil to the init(_:mediaBox:_:). In which case, as docs say:

If you pass NULL, CGPDFContextCreateWithURL uses a default page size of 8.5 by 11 inches (612 by 792 points).

So if that rectangle fits your needs, just pass nil (simpler).

  •  Tags:  
  • Related