Swift: 理解指针
Swift: understanding pointers
我正在尝试使用以下 MacOS Quartz 创建 CoreGraphics 上下文 API:
CGContext.init?(_ url: CFURL,
mediaBox: UnsafePointer<CGRect>?,
_ auxiliaryInfo: CFDictionary?)
,但我对指针的概念有疑问。我可以这样启动上下文:
var mypointer: UnsafeMutablePointer<CGRect>!
mypointer.pointee = myCGRectangle
var writeContext = CGContext.init(outURL, mediaBox: mypointer, nil)
但是它说 pointee
是一个 get-only 属性。我试过:
var mypointer: UnsafePointer<CGRect>! = UnsafePointer(myCGRectangle)
,基于 ,但我得到 cannot convert CGRect to expected type
,以及其他错误。
我在这里查看了其他几个关于指针的问题,但我在其中找不到任何有用的内容。
只需传递对 myCGRectangle
变量的引用,这将创建所需的 UnsafeMutablePointer
:
var writeContext = CGContext(outURL, mediaBox: &myCGRectangle, nil)
确保矩形变量声明为var
,否则&
将不起作用。
可以在 this 出色的 Apple 文档页面上找到有关将指针传递给需要指针的函数的更多详细信息。
通常您不只是创建类型 UnsafeMutablePointer<CGRect>
的变量并将其传递给 init(_:mediaBox:_:)
。您宁愿传递一个将显示 PDF 的矩形,例如
var mediaBox = CGRect(x: 0, y: 0, width: 300, height: 500)
...
var writeContext = CGContext(outURL, mediaBox: &mediaBox, nil)
(这也是一种简化,因为它直接创建了一个矩形。通常你有一些要在其中显示 PDF 的视图矩形,因此你将传递该矩形。)
您也可以将 nil
传递给 init(_:mediaBox:_:)
。在这种情况下,正如文档所说:
If you pass NULL, CGPDFContextCreateWithURL uses a default page size of 8.5 by 11 inches (612 by 792 points).
因此,如果该矩形符合您的需要,只需传递 nil
(更简单)。
我正在尝试使用以下 MacOS Quartz 创建 CoreGraphics 上下文 API:
CGContext.init?(_ url: CFURL,
mediaBox: UnsafePointer<CGRect>?,
_ auxiliaryInfo: CFDictionary?)
,但我对指针的概念有疑问。我可以这样启动上下文:
var mypointer: UnsafeMutablePointer<CGRect>!
mypointer.pointee = myCGRectangle
var writeContext = CGContext.init(outURL, mediaBox: mypointer, nil)
但是它说 pointee
是一个 get-only 属性。我试过:
var mypointer: UnsafePointer<CGRect>! = UnsafePointer(myCGRectangle)
,基于 cannot convert CGRect to expected type
,以及其他错误。
我在这里查看了其他几个关于指针的问题,但我在其中找不到任何有用的内容。
只需传递对 myCGRectangle
变量的引用,这将创建所需的 UnsafeMutablePointer
:
var writeContext = CGContext(outURL, mediaBox: &myCGRectangle, nil)
确保矩形变量声明为var
,否则&
将不起作用。
可以在 this 出色的 Apple 文档页面上找到有关将指针传递给需要指针的函数的更多详细信息。
通常您不只是创建类型 UnsafeMutablePointer<CGRect>
的变量并将其传递给 init(_:mediaBox:_:)
。您宁愿传递一个将显示 PDF 的矩形,例如
var mediaBox = CGRect(x: 0, y: 0, width: 300, height: 500)
...
var writeContext = CGContext(outURL, mediaBox: &mediaBox, nil)
(这也是一种简化,因为它直接创建了一个矩形。通常你有一些要在其中显示 PDF 的视图矩形,因此你将传递该矩形。)
您也可以将 nil
传递给 init(_:mediaBox:_:)
。在这种情况下,正如文档所说:
If you pass NULL, CGPDFContextCreateWithURL uses a default page size of 8.5 by 11 inches (612 by 792 points).
因此,如果该矩形符合您的需要,只需传递 nil
(更简单)。