2017-08-09 3 views
0

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

答えて

1

どのようにatPointを設定していますか?あなたが画面と同じ座標空間を使用している場合、それは動作しません...これは私が起こっていると思われるものです。

あなたの画像が1000 x 2000で、の画像に100 x 200と表示されているとします。ビュー(中央)のx: 50 y: 100をタップしてそのポイントを関数に送信すると、画像のx: 50 y: 100にテキストが描画されます。このテキストは、中央ではなく左上隅に表示されます。

したがって、関数を呼び出す前に、または画像を処理する関数を変更することによって、画像ビューサイズから実際の画像サイズにポイントを変換する必要があります。

例(必ずしもそれを行うための最善の方法):

// assume: 
    // View Size is 100 x 200 
    // Image Size is 1000 x 2000 
    // tapPoint is CGPoint(x: 50, y: 100) 

    let xFactor = image.size.width/imageView.frame.size.width 
    // xFactor now equals 10 

    let yFactor = image.size.height/imageView.frame.size.height 
    // yFactor now equals 10 

    let convertedPoint = CGPoint(x: tapPoint.x * xFactor, y: tapPoint.y * yFactor) 

convertedPointが今するCGPointに等しい(X:500、Y:1000)、そして、あなたはあなたの呼び出しでatPoint値としてそれを送ることができます〜addTextToImage

+0

ありがとう、ありがとう、ありがとう!作品! – Yorma

関連する問題