Gradient 并且存为image

CGGradientRef 的基本步骤
1 创建 CGGradient 对象, 提供一个 colorspace,提供一个数组,包含两个以上的颜色, 提供一个数组,包含两个以上的颜色所处位置, 提供一个数组包含前面两个数组中元素个数.
2 调用CGContextDrawLinearGradient 或者 CGContextDrawRadialGradient ,提供参数 context, CGGradient 对象, drawing options, 开始和结尾的几何形状 (轴向渐变是两个点,径向渐变是圆心和半径).
3 释放CGGradient。

示例 效果图

   
创建一个图形上下文函数
CGContextRef MyCreateBitmapContext (int pixelsWide,
int pixelsHigh)
{
CGContextRef context = NULL;
CGColorSpaceRef colorSpace;
void * bitmapData;
int bitmapByteCount;
int bitmapBytesPerRow;

//声明一个变量来代表每行的字节数。每一个位图像素的代表是4个字节,8bit红,8bit绿,8bit蓝,和8bit alpha通道信息(透明信息)。
bitmapBytesPerRow = (pixelsWide * 4);
bitmapByteCount = (bitmapBytesPerRow * pixelsHigh);

colorSpace = CGColorSpaceCreateDeviceRGB();// 创建一个通用的RGB色彩空间
bitmapData = malloc( bitmapByteCount );// 调用的malloc函数来创建的内存用来存储位图数据块
if (bitmapData == NULL)
{
fprintf (stderr, "Memory not allocated!");
return NULL;
}

//创建一个位图图形上下文
context = CGBitmapContextCreate (bitmapData,
pixelsWide,
pixelsHigh,
8, // bits per component
bitmapBytesPerRow,
colorSpace,
kCGImageAlphaPremultipliedLast);
if (context== NULL)
{
free (bitmapData);
fprintf (stderr, "Context not created!");
return NULL;
}
//释放colorSpace 注意使用的函数
CGColorSpaceRelease( colorSpace );

return context;
}

//在 viewdidload 中添加代码
- (void)viewDidLoad {
[super viewDidLoad];

CGContextRef myBitmapContext = MyCreateBitmapContext (400, 300);

CGGradientRef myGradient;
CGColorSpaceRef myColorspace;
size_t num_locations = 2;
CGFloat locations[2] = { 1.0, 0.0 }; //下面两种颜色所在轴上的位置 是个浮点数,0表示开始位置。1表示结束位置
CGFloat components[8] = { 1.0, 0.0, 0.0, 1.0, // 起始颜色
0.0, 1.0, 0.0, 1.0 }; // 结束颜色

myColorspace = CGColorSpaceCreateDeviceRGB(); //色彩空间 rgb
//创建CGGradient对象
myGradient = CGGradientCreateWithColorComponents (myColorspace, components,
locations, num_locations);

//定义开始开始位置和结束位置
CGPoint myStartPoint, myEndPoint;
myStartPoint.x = 0.0;
myStartPoint.y = 0.0;
myEndPoint.x = 400.0;
myEndPoint.y = 0.0;
CGContextDrawLinearGradient (myBitmapContext, myGradient, myStartPoint, myEndPoint, 0);

////////////
CGImageRef myImage = CGBitmapContextCreateImage (myBitmapContext);
CGContextRelease (myBitmapContext);
UIImageView *iv = [[UIImageView alloc] initWithImage:[UIImage imageWithCGImage:myImage]];
[self.view addSubview:iv];
[iv release];
CGImageRelease(myImage);
}
下面是画一个径向渐变

posted on 2011-04-28 17:23  GaryGaryGary  阅读(184)  评论(0)    收藏  举报

导航