2017-07-13 3 views
2

J'essaye de faire une fonction qui prendra du texte d'un champ de texte (textField) et le dessine sur une image. La fonction pour le moment ne peut changer que les coordonnées du dessin x et y, et la largeur et la hauteur. Ce que je me demandais, c'est comment je peux faire le texte à un angle (par exemple 45˚, 18˚, etc ...)Dessinez un texte sur l'image en l'inclinant [Swift 3]

Merci d'avance.

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 
} 

Répondre

2

1.Tirez d'abord le texte sur une image, puis faites pivoter l'image.

2. Dessinez l'image pivotée (avec du texte) sur l'image d'arrière-plan.

//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

Cela a très bien fonctionné, merci! – Skiddswarmik

+0

U sont les bienvenus, :) –