この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