前段时间公司在研发一个电商项目,趁现在有时间把其中的知识点整理整理。
项目中有个需求是对UIImage的像素值进行改变,小兵当时懵圈了,像素值是撒玩意,还改变?
最后查了百度,其时是对UIImage的RGB进行更改,如下图;
代码
//** 颜色变化 */
void ProviderReleaseData (void *info, const void *data, size_t size){
free((void*)data);
}
- (UIImage*)imageBlackToTransparent:(UIImage*)image withRed:(CGFloat)red andGreen:(CGFloat)green andBlue:(CGFloat)blue{
const int imageWidth = image.size.width;
const int imageHeight = image.size.height;
size_t bytesPerRow = imageWidth * 4;
uint32_t* rgbImageBuf = (uint32_t*)malloc(bytesPerRow * imageHeight);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(rgbImageBuf, imageWidth, imageHeight, 8, bytesPerRow, colorSpace,
kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast);
CGContextDrawImage(context, CGRectMake(0, 0, imageWidth, imageHeight), image.CGImage);
// 遍历像素
int pixelNum = imageWidth * imageHeight;
uint32_t* pCurPtr = rgbImageBuf;
for (int i = 0; i < pixelNum; i++, pCurPtr++){
if ((*pCurPtr & 0xFFFFFF00) < 0x82828200) // 将像素值进行判断
{
// 改成下面的代码,会将图片转成想要的颜色
uint8_t* ptr = (uint8_t*)pCurPtr;
ptr[3] = red; //0~255
ptr[2] = green;
ptr[1] = blue;
// ptr[0] = 0;
}
else
{
uint8_t* ptr = (uint8_t*)pCurPtr;
ptr[0] = 0;
}
}
// 输出图片
CGDataProviderRef dataProvider = CGDataProviderCreateWithData(NULL, rgbImageBuf, bytesPerRow * imageHeight, ProviderReleaseData);
CGImageRef imageRef = CGImageCreate(imageWidth, imageHeight, 8, 32, bytesPerRow, colorSpace,
kCGImageAlphaLast | kCGBitmapByteOrder32Little, dataProvider,
NULL, true, kCGRenderingIntentDefault);
CGDataProviderRelease(dataProvider);
UIImage* resultUIImage = [UIImage imageWithCGImage:imageRef];
// 清理空间
CGImageRelease(imageRef);
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
return resultUIImage;
}
RGB用法
0xFFFFFF00 0x表示16进制数,前两个ff表示的是透明度,00-ff,接下来两个ff表示红R,00-ff,后面两个ff表示绿G,00-ff,最后两个ff表示蓝B,00-ff,所以呢int mul = 0xFFFFFF00;
//remove BLUE component 移除蓝色B部分,可以根据三基色配色图看int add = 0x0000FF00;
//set GREEN full 绿色的填满,差不多就这个意思了。。。具体的还可以去测试下float[] colorMatrix = {
1, 0, 0, 0, 0, //red
0, 0, 0, 0, 0, //green
0, 0, 0, 0, 0, //blue
0, 0, 0, 1, 0 //alpha
};
Paint MyPaint = new Paint();
ColorFilter colorFilter = new ColorMatrixColorFilter(colorMatrix);
MyPaint.setColorFilter(colorFilter);
Bitmap myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
canvas.drawBitmap(myBitmap, 100, 100, MyPaint);
};这个画出来的效果就是红色和黑色了,因为不透明,这个是color矩阵的用法,不太懂矩阵。
RGB 宏
iOS中RGB常用的色值,同时可将对颜色的设置定义成宏,方便开发应用,如:
// RGB颜色转换(16进制->10进制)
#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
// 获取RGB颜色
#define RGBA(r,g,b,a) [UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:a]
#define RGB(r,g,b) RGBA(r,g,b,1.0f)