我使用this post中的此功能将彩色图像转换为灰度图像:
func grayScaleImage() -> UIImage {
let imageRect = CGRectMake(0, 0, self.size.width, self.size.height);
let colorSpace = CGColorSpaceCreateDeviceGray();
let width = UInt(self.size.width)
let height = UInt(self.size.height)
let context = CGBitmapContextCreate(nil, width, height, 8, 0, colorSpace, .allZeros);
CGContextDrawImage(context, imageRect, self.CGImage!);
let imageRef = CGBitmapContextCreateImage(context);
let newImage = UIImage(CGImage: imageRef)
return newImage
}
我对一些具有透明背景的图像进行了一些测试,我得到的结果是带有黑色背景的图像。我希望透明/半透明像素的行为就好像图像的背景是白色的,我该怎么做?
答案 0 :(得分:0)
要使图像的透明部分为白色(或任何其他颜色),只需在绘图上下文中绘制一个填充的矩形。
斯威夫特3:
extension UIImage {
func grayScaleImage() -> UIImage {
let imageRect = CGRectMake(0, 0, self.size.width, self.size.height);
let colorSpace = CGColorSpaceCreateDeviceGray();
let width = Int(self.size.width)
let height = Int(self.size.height)
let context = CGBitmapContextCreate(nil, width, height, 8, 0, colorSpace, .allZeros);
// set Fill Color to White (or some other color)
CGContextSetFillColorWithColor(context, UIColor.whiteColor().CGColor)
// Draw a white-filled rectangle before drawing your image
CGContextFillRect(context, imageRect)
CGContextDrawImage(context, imageRect, self.CGImage!);
let imageRef = CGBitmapContextCreateImage(context);
let newImage = UIImage(CGImage: imageRef!)
return newImage
}
}
Swift 2.2:
library(ggplot2)
dd <- data.frame(x=factor(c(1,-1,2:10),levels=c(1,-1,2:10)), y=c(1,2,2:10), hidden=as.factor(c(0,1,rep(0,9))))
ggplot(data=dd,aes(x=x,y=y,alpha=hidden)) +
geom_point() + scale_alpha_manual(values=c("1"=0,"0"=1)) +
scale_x_discrete(breaks=c(1:10))