2016-08-22 118 views

回答

3

您可以設置UIGraphicsImageRenderer創建一個圖像,並與調用UIGraphicsGetCurrentContext()和旋轉方面

let renderer = UIGraphicsImageRenderer(size:sizeOfImage) 
    let image = renderer.image(actions: { _ in 
     let context = UIGraphicsGetCurrentContext() 

     context?.translateBy(x: orgin.x, y: orgin.y) 
     context?.rotate(by: angle) 
     context?.draw(image.cgImage!, in: CGRect(origin: CGPoint(x: -orgin.x,y: -orgin.y), size: size)) 
    } 
return image 
1

請仔細閱讀文檔,也由於缺乏對這個問題的回覆,我認爲這是不可能的新的UIGraphicsImageRenderer。這是我如何解決它在一天結束:

func changeImageRotation(forImage image:UIImage, rotation alpha:CGFloat) -> UIImage{ 

    var newSize:CGSize{ 
     let a = image.size.width 
     let b = image.size.height 

     let width = abs(cos(alpha)) * a + abs(sin(alpha)) * b 
     let height = abs(cos(alpha)) * b + abs(sin(alpha)) * a 

     return CGSize(width: width, height: height) 
    } 

    let size = newSize 
    let orgin = CGPoint(x: size.width/2, y: size.height/2) 

    UIGraphicsBeginImageContext(size) 
    let context = UIGraphicsGetCurrentContext() 

    context?.translateBy(x: orgin.x, y: orgin.y) 
    context?.rotate(by: alpha) 
    context?.draw(image.cgImage!, in: CGRect(origin: CGPoint(x: -orgin.x,y: -orgin.y), size: size)) 

    let newImage = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 

    return newImage! 
} 

New Size對應於需要繪製旋轉的圖像,而不改變其整體尺寸的矩形區域。圖像不是旋轉並繪製在中心。有關更多信息,請參閱此post