以一定角度在文字上绘制文字[Swift 3]

时间:2017-07-13 01:18:40

标签: ios swift swift3 rotation draw

我正在尝试创建从文本字段(textField)获取文本并将其绘制到图像上的函数。此刻的功能只能改变图形的坐标x和y,以及宽度和高度。我想知道的是我如何能够以一定的角度绘制文本(例如45˚,18˚等......)

提前致谢。

func drawText() {
    let font = UIFont.boldSystemFont(ofSize: 30)
    let showText:NSString = textField.text as! NSString
    // setting attr: font name, color...etc.
    let attr = [NSFontAttributeName: font, NSForegroundColorAttributeName:UIColor.white]
    // getting size
    let sizeOfText = showText.size(attributes: attr)

    let image = UIImage(named: "image")!
    let rect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)

    UIGraphicsBeginImageContextWithOptions(CGSize(width: rect.size.width, height: rect.size.height), true, 0)

    // drawing our image to the graphics context
    image.draw(in: rect)
    // drawing text
    showText.draw(in: CGRect(x: rect.size.width-sizeOfText.width-10, y: rect.size.height-sizeOfText.height-10, width: rect.size.width, height: rect.size.height), withAttributes: attr)

    // getting an image from it
    let newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext()

    self.imageView.image = newImage
}

1 个答案:

答案 0 :(得分:2)

1.首先将文本绘制到图像,然后旋转图像。

2.将旋转后的图像(带文字)拖到背景图像上。

    //First create the rotated and transparent image with text        
    UIGraphicsBeginImageContextWithOptions(CGSize(width: rect.size.width, height: rect.size.height), false, 0)
    if let context = UIGraphicsGetCurrentContext() {
        context.rotate (by: 45.0 * CGFloat.pi/180.0) //45˚
    }
    showText.draw(in: CGRect(x: 10, y: 10, width: rect.size.width, height: rect.size.height), withAttributes: attr)
    let rotatedImageWithText = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext()


    //Then, draw rotated image(with text) onto the background image
    UIGraphicsBeginImageContextWithOptions(CGSize(width: rect.size.width, height: rect.size.height), true, 0)

    image.draw(in: rect)
    rotatedImageWithText?.draw(in: rect)

    let newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext()

    self.imageView.image = newImage