以一定角度将文本绘制到图像上 [Swift 3]



我正在尝试制作函数,该函数将从文本字段(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.先将文本绘制到图像,然后旋转图像。

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

最新更新