iOS在形状中心绘制文本 [英] iOS Drawing text in the centre of shapes

查看:87
本文介绍了iOS在形状中心绘制文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在iOS中的形状中心绘制文本,例如Microsoft Office的插入形状请参阅:


I'm trying to draw text in the centre of shapes in iOS, an example would be Microsoft Office's insert shape see: https://www.dropbox.com/s/cgqyyuvy6hcv5g8/Screenshot%202014-01-21%2013.48.17.png

I have an array of coordinates that are used to form the shape, which works fine for creating the actual shape.

My first tactic was following this stackoverflow question: Core Text With Asymmetric Shape on iOS however I can only get it to draw the text at the bottom of the shape. Is there any way to centre the text vertically and horizontally?

I then had a look at the new TextKit but I got stuck with how to subclass NSTextContainer to accept either a CGPath or an array of coordinates to create the text container to draw inside.

My backup solution is to use Core Text to draw the text at the centre coordinate of a shape, however this will cause the text to draw outside of the shape on some shapes such as a right angled triangle.

Alternatively, are there any other methods I could use to get some text somewhat in the centre of a shape?

Thank you,

Danielle.

解决方案

I cherrypicked from these answers and from related questions - none of them were truly satisfying - and came up with this simple solution:

    UIGraphicsBeginImageContext(CGSize.init(width: imageWidth, height: imageHeight))

    let string = "ABC" as NSString

    let attributes = [
            NSFontAttributeName : UIFont.systemFontOfSize(40),
            NSForegroundColorAttributeName : UIColor.redColor()
        ]

    // Get the width and height that the text will occupy.
    let stringSize = string.sizeWithAttributes(attributes)

    // Center a rect inside of the image
    // by going half the difference to the right and down.
    string.drawInRect(
        CGRectMake(
            (imageWidth - stringSize.width) / 2,
            (imageHeight - stringSize.height) / 2,
            stringSize.width,
            stringSize.height
        ),
        withAttributes: attributes
    )

    let newImage = UIGraphicsGetImageFromCurrentImageContext()

    UIGraphicsEndImageContext()

The result (nevermind the colours):

这篇关于iOS在形状中心绘制文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆