【问题标题】:How use CGContextDrawImage in Swift 3? [duplicate]如何在 Swift 3 中使用 CGContextDrawImage? [复制]
【发布时间】:2016-09-29 12:08:57
【问题描述】:

我有一个使用CGContextDrawImageUIImage 扩展。 它只是旋转UIImage。 我更新到 Xcode8 和 Swift3 并且不知道如何使用 CGContextDrawImage

我在 CGContextDrawImage 上遇到错误。

“无法将“CGImage.Type”类型的值转换为预期的参数类型“CGImage?””

我的代码是:

CGContextDrawImage(bitmap, CGRectMake(-size.width / 2, -size.height / 2, size.width, size.height), CGImage)

以及整个扩展:

extension UIImage {
public func imageRotatedByDegrees(degrees: CGFloat, flip: Bool) -> UIImage {
    let radiansToDegrees: (CGFloat) -> CGFloat = {
        return $0 * (180.0 / CGFloat(M_PI))
    }
    let degreesToRadians: (CGFloat) -> CGFloat = {
        return $0 / 180.0 * CGFloat(M_PI)
    }

    // calculate the size of the rotated view's containing box for our drawing space
    let rectZero = CGPoint(dictionaryRepresentation: CGRect.zero as! CFDictionary)
    let rotatedViewBox = UIView(frame: CGRect(origin: rectZero!, size: size))
    let t = CGAffineTransform(rotationAngle: degreesToRadians(degrees));
    rotatedViewBox.transform = t
    let rotatedSize = rotatedViewBox.frame.size

    // Create the bitmap context
    UIGraphicsBeginImageContext(rotatedSize)
    let bitmap = UIGraphicsGetCurrentContext()

    // Move the origin to the middle of the image so we will rotate and scale around the center.
    bitmap!.translateBy(x: rotatedSize.width / 2.0, y: rotatedSize.height / 2.0);

    //   // Rotate the image context
    bitmap!.rotate(by: degreesToRadians(degrees));

    // Now, draw the rotated/scaled image into the context
    var yFlip: CGFloat

    if(flip){
        yFlip = CGFloat(-1.0)
    } else {
        yFlip = CGFloat(1.0)
    }

    bitmap!.scaleBy(x: yFlip, y: -1.0)

    CGContextDrawImage(bitmap, CGRectMake(-size.width / 2, -size.height / 2, size.width, size.height), CGImage)

    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage!
}
}

【问题讨论】:

  • 不幸的是,使用“cgcontextdrawimage swift3”搜索并没有引导我进入主题...感谢您找到它!。

标签: ios swift swift3 cgcontextdrawimage


【解决方案1】:

在 Swift 3 中,CGContext 的许多函数作为CGContext 的实例方法导入,属性名称CGImage 已重命名为cgImage。并且CGRectMake 被删除。

试试这个:

    bitmap!.draw(cgImage!, in: CGRect(x: -size.width / 2, y: -size.height / 2, width: size.width, height: size.height))

(希望! 对您的使用安全。)

func draw(CGImage, in: CGRect, byTiling: Bool)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-29
    • 2018-04-29
    • 2014-09-14
    • 2016-07-13
    • 2017-04-23
    • 2017-02-17
    相关资源
    最近更新 更多