gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 01:18:35 27 4
gpt4 key购买 nike

我正在尝试制作将从文本字段 (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

关于ios - 以一定角度将文本绘制到图像上 [Swift 3],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45069931/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com