2017-08-09 38 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