我有这个Objective-C代码,它取出了过滤器的不透明背景。我试图将它转换为最新的Swift并且在整个地方都有错误。
DataProtectorTokenProvider
当我逐行转换时。我已经做到了这一点,但在转换线路方面存在问题:
DM_a(0 until M, ::)
答案 0 :(得分:0)
我相信以下是原始代码的正确端口:
func removeColorFromImage(sourceImage: UIImage, grayLevel: UInt32) -> UIImage? {
let scale = sourceImage.scale
let width = Int(sourceImage.size.width * scale)
let height = Int(sourceImage.size.height * scale)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGBitmapInfo.AlphaInfoMask.rawValue & CGImageAlphaInfo.PremultipliedFirst.rawValue)
let context = CGBitmapContextCreate(nil, width, height, 8, width * 4, colorSpace, bitmapInfo.rawValue)
CGContextDrawImage(context, CGRectMake(0, 0, CGFloat(width), CGFloat(height)), sourceImage.CGImage)
let uncastedData = CGBitmapContextGetData(context)
let colorData = UnsafeMutablePointer<UInt32>(uncastedData)
for i in 0..<width * height {
let color = colorData[i]
var a = color & 0xFF
var r = (color >> 8) & 0xFF
var g = (color >> 16) & 0xFF
var b = (color >> 24) & 0xFF
if ((r == grayLevel) && (g == grayLevel) && (b == grayLevel)) {
(a, r, g, b) = (0, 0, 0, 0)
colorData[i] = (r << 8) + (g << 16) + (b << 24) + a
}
colorData.advancedBy(1)
}
if let output = CGBitmapContextCreateImage(context) {
return UIImage(CGImage: output, scale: scale, orientation: UIImageOrientation.Up)
}
return nil
}
以下是一个示例(原始 - &gt;输出):
removeColorFromImage(original, grayLevel: 175)
解释更改
自Swift 2(我相信)以来,你必须使用rawValue作为CGBitmapContextCreate的最后一个参数:
let context = CGBitmapContextCreate(nil, width, height, 8, width * 4, colorSpace, bitmapInfo.rawValue)
此外,在您的端口中,您没有使用Objective-C代码中的原始值:
// your new code was just using CGImageAlphaInfo.PremultipliedFirst.rawValue
// to match, it should be:
let bitmapInfo = CGBitmapInfo(rawValue: CGBitmapInfo.AlphaInfoMask.rawValue & CGImageAlphaInfo.PremultipliedFirst.rawValue)
你在C风格for循环中所做的位移是在无效类型上。它现在在UInt32s上。我也为你摆脱了C风格的循环警告:)
最后,您需要使用它来初始化最终的UIImage:
UIImage(CGImage: output, scale: scale, orientation: UIImageOrientation.Up)
您尝试使用的类功能无效。