1创建一个基于window的程序
2创建一个viewcontroller
3创建一个UIView的子类 将上述文件关联起来,
即在AppDelegate.m中 [window addSubview:myViewController.view];
在MyviewController.m中的loadview函数中创建一个 UIView子类的实例,self.view = myview ;
并重写myView的drawRect函数。
第一个例子:
在drawRect函数中,如下:
CGContextRef myContext = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor (myContext, 1, 0, 0, 1);
CGContextFillRect (myContext, CGRectMake (0, 0, 200, 100 ));
CGContextSetRGBFillColor (myContext, 0, 0, 1, .5);
CGContextFillRect (myContext, CGRectMake (0, 0, 100, 200));
第二个例子,是画image的,同样在drawRect中,代码如下:
int myWidth = 320 ;
int myHeight = 480;
//UIImage myImage;
CGRect myBoundingBox = CGRectMake (0, 0, myWidth, myHeight);
CGContextRef myBitmapContext = createBitmapContext(400, 300);
// ********** Your drawing code here **********//
CGContextSetRGBFillColor (myBitmapContext, 1, 0, 0, 1);
CGContextFillRect (myBitmapContext, CGRectMake (0, 0, 200, 100 ));
CGContextSetRGBFillColor (myBitmapContext, 0, 0, 1, .5);
CGContextFillRect (myBitmapContext, CGRectMake (0, 0, 100, 200 ));
CGImageRef myImage = CGBitmapContextCreateImage (myBitmapContext);
CGContextDrawImage(myContext, myBoundingBox, myImage);
char *bitmapData = CGBitmapContextGetData(myBitmapContext);
CGContextRelease (myBitmapContext);
if (bitmapData) free(bitmapData);
CGImageRelease(myImage);
//其中createBitmapContext函数的实现如下:
CGContextRef createBitmapContext (int pixelsWide,int pixelsHigh) {
CGContextRef context = NULL;
CGColorSpaceRef colorSpace ;
void * bitmapData;
int bitmapByteCount;
int bitmapBytesPerRow;
bitmapBytesPerRow = (pixelsWide * 4);
//1
bitmapByteCount = (bitmapBytesPerRow * pixelsHigh);
colorSpace = CGColorSpaceCreateDeviceRGB();
//2
bitmapData = malloc( bitmapByteCount );
//3
if (bitmapData == NULL) {
fprintf (stderr, "Memory not allocated!"); return NULL;
}
context = CGBitmapContextCreate(bitmapData, pixelsWide, pixelsHigh, 8, bitmapBytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast);
if (context== NULL) {
free(bitmapData);
fprintf(stderr, "dada");
return NULL;
}
CGColorSpaceRelease(colorSpace);
return context;
}
沒有留言:
張貼留言