【发布时间】:2016-05-04 21:09:47
【问题描述】:
我有这个 Objective-C 代码,它可以去除过滤器的不透明背景。我正在尝试将其转换为最新的 Swift,并且到处都有错误。
-(UIImage*)removeColorFromImage:(UIImage*)sourceImage grayLevel:(int)grayLevel
{
int width = sourceImage.size.width * sourceImage.scale;
int height = sourceImage.size.height * sourceImage.scale;
CGFloat scale = sourceImage.scale;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8, width * 4, colorSpace, kCGBitmapAlphaInfoMask & kCGImageAlphaPremultipliedFirst);
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), sourceImage.CGImage);
unsigned int *colorData = CGBitmapContextGetData(context);
for (int i = 0; i < width * height; i++)
{
unsigned int color = *colorData;
short a = color & 0xFF;
short r = (color >> 8) & 0xFF;
short g = (color >> 16) & 0xFF;
short b = (color >> 24) & 0xFF;
if ((r == grayLevel) && (g == grayLevel) && (b == grayLevel))
{
a = r = g = b = 0;
*colorData = (unsigned int)(r << 8) + ((unsigned int)(g) << 16) + ((unsigned int)(b) << 24) + ((unsigned int)(a));
}
colorData++;
}
CGImageRef output = CGBitmapContextCreateImage(context);
UIImage* retImage = [UIImage imageWithCGImage:output scale:scale orientation:UIImageOrientationUp];
CGImageRelease(output);
CGContextRelease(context);
return retImage;
}
当我逐行转换时。我已经做到了这一点,但在转换行时遇到问题:
var context = CGBitmapContextCreate(nil, width, height, 8, width * 4, colorSpace, CGBitmapInfo(CGImageAlphaInfo.PremultipliedFirst.rawValue))
【问题讨论】:
-
错误是什么?看起来你错过了我的
rawValue:初始化参数(CGBitmapInfo)。context也很可能是let常量。 -
更新了原帖。
-
为什么要转换成 swift 代码?为什么不使用 bridge 快速使用目标 c 代码? developer.apple.com/library/ios/documentation/Swift/Conceptual/…
标签: objective-c xcode swift cgimage cgbitmapcontext