2017-07-13 38 views
2

我想要使文本從文本字段(textField),並將其繪製到圖像上的函數。此時的功能只能更改圖形的座標x和y以及寬度和高度。我想知道的是,我怎樣才能使文本以一定角度繪製(例如45˚,18˚等...)在一個角度上的圖像上繪製文本[斯威夫特3]

在此先感謝。

func drawText() { 
    let font = UIFont.boldSystemFont(ofSize: 30) 
    let showText:NSString = textField.text as! NSString 
    // setting attr: font name, color...etc. 
    let attr = [NSFontAttributeName: font, NSForegroundColorAttributeName:UIColor.white] 
    // getting size 
    let sizeOfText = showText.size(attributes: attr) 

    let image = UIImage(named: "image")! 
    let rect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height) 

    UIGraphicsBeginImageContextWithOptions(CGSize(width: rect.size.width, height: rect.size.height), true, 0) 

    // drawing our image to the graphics context 
    image.draw(in: rect) 
    // drawing text 
    showText.draw(in: CGRect(x: rect.size.width-sizeOfText.width-10, y: rect.size.height-sizeOfText.height-10, width: rect.size.width, height: rect.size.height), withAttributes: attr) 

    // getting an image from it 
    let newImage = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext() 

    self.imageView.image = newImage 
} 

回答

2

1.先將文本繪製到圖像上,然後旋轉圖像。

2.將圖像(帶文字)旋轉到背景圖像上。

//First create the rotated and transparent image with text   
    UIGraphicsBeginImageContextWithOptions(CGSize(width: rect.size.width, height: rect.size.height), false, 0) 
    if let context = UIGraphicsGetCurrentContext() { 
     context.rotate (by: 45.0 * CGFloat.pi/180.0) //45˚ 
    } 
    showText.draw(in: CGRect(x: 10, y: 10, width: rect.size.width, height: rect.size.height), withAttributes: attr) 
    let rotatedImageWithText = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext() 


    //Then, draw rotated image(with text) onto the background image 
    UIGraphicsBeginImageContextWithOptions(CGSize(width: rect.size.width, height: rect.size.height), true, 0) 

    image.draw(in: rect) 
    rotatedImageWithText?.draw(in: rect) 

    let newImage = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext() 

    self.imageView.image = newImage 
+0

這真的很好,謝謝! – Skiddswarmik

+0

歡迎光臨,:) –