開啓此Stackoverflow post,這非常有幫助,我已經能夠成功地將文本繪製成全屏圖像,屏幕圖像(我標記的圖像與前罐頭,短字符串,例如,「回收站」)。但是,該文本並未出現在我想要的位置,而是以用戶點擊的確切位置爲中心。這裏是我的代碼的基礎上,從上面發佈一些代碼,但更新的Swift3 -Swift 3 - NSString.draw(in:rect,withAttributes :) - 未在預期點繪製文字
func addTextToImage(text: NSString, inImage: UIImage, atPoint:CGPoint) -> UIImage{
// Setup the font specific variables
let textColor: UIColor = UIColor.red
let textFont: UIFont = UIFont(name: "Helvetica Bold", size: 80)!
//Setups up the font attributes that will be later used to dictate how the text should be drawn
let textFontAttributes = [
NSFontAttributeName: textFont,
NSForegroundColorAttributeName: textColor,
]
// Create bitmap based graphics context
UIGraphicsBeginImageContextWithOptions(inImage.size, false, 0.0)
//Put the image into a rectangle as large as the original image.
inImage.draw(in: CGRect(x:0, y:0, width:inImage.size.width, height: inImage.size.height))
// Create the rectangle where the text will be written
let rect: CGRect = CGRect(x:atPoint.x, y:atPoint.y, width:inImage.size.width, height: inImage.size.height)
// Draft the text in the rectangle
text.draw(in: rect, withAttributes: textFontAttributes)
// Get the image from the graphics context
let newImag = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImag!
}
在上面,atPoint是用戶的敲擊的位置。這是我想要繪製文本的地方。但是,文本總是寫入圖像的左上角。例如,附加的圖像中,我已經利用中途而下的瀑布,因爲這是我想要的寫入文本字符串「回收站」。但是,您可以看到它在左上角寫着。我嘗試了一堆東西,但無法獲得解決方案。我感謝任何幫助。 enter image description here
TrashShouldBeInMiddleOfWaterfallButIsNot
謝謝你,謝謝你,謝謝你!作品! – Yorma