美文网首页
Fix Swift Orientation

Fix Swift Orientation

作者: HenrySHE | 来源:发表于2017-11-29 12:13 被阅读0次

    Just repost and make it readable rather than plain text.

    just call the function "cell.imageView.image = fixOrientation(myPhoto)"

    func fixOrientation(aImage: UIImage) -> UIImage {
    
    if (aImage.imageOrientation == .Up) {
    
    return aImage
    
    }
    
    var transform = CGAffineTransformIdentity
    
    switch (aImage.imageOrientation) {
    
    case .Down, .DownMirrored:
    
    transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height)
    
    transform = CGAffineTransformRotate(transform, CGFloat(M_PI))
    
    case .Left, .LeftMirrored:
    
    transform = CGAffineTransformTranslate(transform, aImage.size.width, 0)
    
    transform = CGAffineTransformRotate(transform, CGFloat(M_PI_2))
    
    case .Right, .RightMirrored:
    
    transform = CGAffineTransformTranslate(transform, 0, aImage.size.height)
    
    transform = CGAffineTransformRotate(transform, CGFloat(-M_PI_2))
    
    default:
    
    break
    
    }
    
    switch (aImage.imageOrientation) {
    
    case .UpMirrored, .DownMirrored:
    
    transform = CGAffineTransformTranslate(transform, aImage.size.width, 0)
    
    transform = CGAffineTransformScale(transform, -1, 1)
    
    case .LeftMirrored, .RightMirrored:
    
    transform = CGAffineTransformTranslate(transform, aImage.size.height, 0)
    
    transform = CGAffineTransformScale(transform, -1, 1)
    
    default:
    
    break
    
    }
    
    let ctx = CGBitmapContextCreate(nil, Int(aImage.size.width), Int(aImage.size.height),
    
    CGImageGetBitsPerComponent(aImage.CGImage), 0,
    
    CGImageGetColorSpace(aImage.CGImage),
    
    CGImageGetBitmapInfo(aImage.CGImage))
    
    CGContextConcatCTM(ctx, transform)
    
    switch (aImage.imageOrientation) {
    
    case .Left, .LeftMirrored, .Right, .RightMirrored:
    
    CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage)
    
    default:
    
    CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage)
    
    }
    
    // And now we just create a new UIImage from the drawing context
    
    let cgimg = CGBitmapContextCreateImage(ctx)
    
    return UIImage(CGImage: cgimg!)!
    
    }
    
    作者:codeFarmer
    链接:http://www.jianshu.com/p/a7fb8fc1744c
    來源:简书
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
    

    相关文章

      网友评论

          本文标题:Fix Swift Orientation

          本文链接:https://www.haomeiwen.com/subject/smeubxtx.html