Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/117.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios Swift-游乐场-核心图形/核心文本/自定义视图 问题:_Ios_Xcode_Swift_Core Graphics_Core Text - Fatal编程技术网

Ios Swift-游乐场-核心图形/核心文本/自定义视图 问题:

Ios Swift-游乐场-核心图形/核心文本/自定义视图 问题:,ios,xcode,swift,core-graphics,core-text,Ios,Xcode,Swift,Core Graphics,Core Text,我正在尝试在swift游乐场中创建自定义UIView组件。除了正确渲染文本之外,我已经能够想出如何做所有事情。我不确定我是否应该通过核心图形或核心文本来实现这一点,或者确切地说如何让它正常工作 正如您在下图中所看到的,我希望在自定义视图组件的任一侧上呈现倒置和右侧向上的文本 我已经尝试了各种方法来让这篇文章起作用,但我一直搁浅。如果有人能告诉我如何修改我的游乐场,添加一些文本渲染,那将是非常棒的 游乐场守则 我为我的应用程序编写了一个实用函数,使用CoreText绘制文本。 它返回文本大小以供

我正在尝试在swift游乐场中创建自定义UIView组件。除了正确渲染文本之外,我已经能够想出如何做所有事情。我不确定我是否应该通过核心图形或核心文本来实现这一点,或者确切地说如何让它正常工作

正如您在下图中所看到的,我希望在自定义视图组件的任一侧上呈现倒置和右侧向上的文本

我已经尝试了各种方法来让这篇文章起作用,但我一直搁浅。如果有人能告诉我如何修改我的游乐场,添加一些文本渲染,那将是非常棒的

游乐场守则
我为我的应用程序编写了一个实用函数,使用
CoreText
绘制文本。 它返回文本大小以供进一步处理:

func drawText(context: CGContextRef, text: NSString, attributes: [String: AnyObject], x: CGFloat, y: CGFloat) -> CGSize {
    let font = attributes[NSFontAttributeName] as UIFont
    let attributedString = NSAttributedString(string: text, attributes: attributes)

    let textSize = text.sizeWithAttributes(attributes)

    // y: Add font.descender (its a negative value) to align the text at the baseline
    let textPath    = CGPathCreateWithRect(CGRect(x: x, y: y + font.descender, width: ceil(textSize.width), height: ceil(textSize.height)), nil)
    let frameSetter = CTFramesetterCreateWithAttributedString(attributedString)
    let frame       = CTFramesetterCreateFrame(frameSetter, CFRange(location: 0, length: attributedString.length), textPath, nil)

    CTFrameDraw(frame, context)

    return textSize
}
这样说吧:

var textAttributes: [String: AnyObject] = [
    NSForegroundColorAttributeName : UIColor(white: 1.0, alpha: 1.0).CGColor,
    NSFontAttributeName : UIFont.systemFontOfSize(17)
]

drawText(ctx, text: "Hello, World!", attributes: textAttributes, x: 50, y: 50)

希望这能对你有所帮助。

为什么会画颠倒?@Alexander:在iOS中,你需要先翻转坐标系。
CGRect.integral
(Swift 3)或
CGRect.integral(rect)
(Swift 2)比
ceil
var textAttributes: [String: AnyObject] = [
    NSForegroundColorAttributeName : UIColor(white: 1.0, alpha: 1.0).CGColor,
    NSFontAttributeName : UIFont.systemFontOfSize(17)
]

drawText(ctx, text: "Hello, World!", attributes: textAttributes, x: 50, y: 50)