我正在尝试绘制到位图上下文但是空出来了。我相信我正在创造正确的东西,因为我可以初始化上下文,绘制一些东西,然后从中创建一个图像并绘制该图像。我不能做的是,在初始化之后,触发进一步绘制在其上绘制更多项目的上下文。我不确定我是否缺少一些常见的做法,这意味着我只能在某些地方画画,或者我必须做别的事情。以下是我的工作,下面。
我复制了苹果公司提供的辅助功能,并进行了一次修改,以获得色彩空间,因为它没有编译(这适用于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方法中,我从中创建一个图像来渲染它。也许我应该创建并保持此图像作为成员var并在每次绘制新内容时更新它而不是每帧都创建图像? (对此有一些建议会很好):
// 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);
}
帮助?
答案 0 :(得分:1)
[self setNeedsDisplay]; !!!!
!!!!!!!!!
所以这是因为在init之后永远不会调用drawRect,因为它不知道需要刷新。我的理解是,我应该在绘制时随时调用setNeedsDisplay,这似乎有效。 :)