2017-08-09 34 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,並且您在UIImageView100 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