我想绘制到位图上下文但空来。我相信我正在创造一些东西,因为我可以初始化上下文,绘制一些东西,然后从中创建一个图像并绘制该图像。我不能做的是,在初始化之后,触发进一步绘制在其上绘制更多项目的上下文。我不确定我是否忽略了一些常见的做法,这意味着我只能在某些地方绘制它,或者我必须做其他事情。下面是我做的。绘制到位图上下文
我复制了苹果公司提供的辅助功能用一个修改,以获得色彩空间,因为它不是编译(这是适用于iPad,不知道是否该事项):
CGContextRef MyCreateBitmapContext (int pixelsWide, int pixelsHigh)
{
CGContextRef context = NULL;
CGColorSpaceRef colorSpace;
void * bitmapData;
int bitmapByteCount;
int bitmapBytesPerRow;
bitmapBytesPerRow = (pixelsWide * 4);// 1
bitmapByteCount = (bitmapBytesPerRow * pixelsHigh);
colorSpace = CGColorSpaceCreateDeviceRGB(); //CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);// 2
bitmapData = malloc(bitmapByteCount);// 3
if (bitmapData == NULL)
{
fprintf (stderr, "Memory not allocated!");
return NULL;
}
context = CGBitmapContextCreate (bitmapData,// 4
pixelsWide,
pixelsHigh,
8, // bits per component
bitmapBytesPerRow,
colorSpace,
kCGImageAlphaPremultipliedLast);
if (context== NULL)
{
free (bitmapData);// 5
fprintf (stderr, "Context not created!");
return NULL;
}
CGColorSpaceRelease(colorSpace);// 6
return context;// 7
}
我初始化它在下面几样我的init()方法绘制只是要确保它看起来是正确的:
mContext = MyCreateBitmapContext (rect.size.width, rect.size.height);
// sample fills
CGContextSetRGBFillColor (mContext, 1, 0, 0, 1);
CGContextFillRect (mContext, CGRectMake (0, 0, 200, 100));
CGContextSetRGBFillColor (mContext, 0, 0, 1, .5);
CGContextFillRect (mContext, CGRectMake (0, 0, 100, 200));
CGContextSetRGBStrokeColor(mContext, 1.0, 1.0, 1.0, 1.0);
CGContextSetRGBFillColor(mContext, 0.0, 0.0, 1.0, 1.0);
CGContextSetLineWidth(mContext, 5.0);
CGContextAddEllipseInRect(mContext, CGRectMake(0, 0, 60.0, 60.0));
CGContextStrokePath(mContext);
在我的drawRect方法,我创建一个图像从它呈现它。也许我应该创建并保持这个图像作为一个成员变种,并更新它,每次我画新的东西,而不是每帧创建图像? (关于这方面的一些建议是很好的):
// draw bitmap context
CGImageRef myImage = CGBitmapContextCreateImage (mContext);
CGContextDrawImage(context, rect, myImage);
CGImageRelease(myImage);
然后作为一个测试,我试着画一个圆圈,当我触摸到,但没有任何反应,并且触摸绝对是触发:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
CGPoint location;
for (UITouch* touch in touches)
{
location = [touch locationInView: [touch view]];
}
CGContextSetRGBStrokeColor(mContext, 1.0, 1.0, 1.0, 1.0);
CGContextSetRGBFillColor(mContext, 0.0, 0.0, 1.0, 1.0);
CGContextSetLineWidth(mContext, 2.0);
CGContextAddEllipseInRect(mContext, CGRectMake(location.x, location.y, 60.0, 60.0));
CGContextStrokePath(mContext);
}
帮助?
您可以通过点击绿色勾号“接受”您自己的答案... – 2015-06-08 13:11:11