【发布时间】:2011-03-31 14:56:11
【问题描述】:
我是 Objective C 的新手。 我正在尝试将(到目前为止的基本线条)绘制到位图上,然后将位图呈现在 Iphone 的屏幕上。
以下是我尝试过的代码,它只显示一个空白屏幕:
- (void)drawRect:(CGRect)rect
{
CGContextRef screen = UIGraphicsGetCurrentContext();
size_t width = rect.size.width;
size_t height = rect.size.height;
void *data = malloc(width*height*4);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef c = CGBitmapContextCreate(data, width, height, 8, width*4, colorSpace, kCGImageAlphaPremultipliedFirst);
CGFloat black[4] = {0.0f,0.0f,0.0f,1.0f}; // setting the color in CMYK format
CGContextSetStrokeColor(c, black);
CGContextBeginPath(c);
CGContextMoveToPoint(c, 5.0f, 5.0f);
CGContextAddLineToPoint(c, 50.0f, 50.0f);
CGContextAddLineToPoint(c, 100.0f, 60.0f);
CGContextMoveToPoint(c, 100.0f, 100.0f);
CGContextAddLineToPoint(c, 50.0f, 150.0f);
CGContextStrokePath(c);
CGImageRef img = CGBitmapContextCreateImage(c);
CFRelease(c);
free(data);
CGContextDrawImage(screen, rect, img);
CGContextFlush(screen);
CGContextFlush(c);
CFRelease(colorSpace);
CGImageRelease(img);
CFRelease(screen);
}
如果有人能指出类似的例子或建议对我的代码进行更改,请告诉我。
感谢大家的帮助... 代码有效,但与预期不符。
我修改代码如下:
CGContextSetRGBFillColor(screen, 1.0, 1.0, 1.0, 1.0); //code works without these 3 lines
CGContextFillRect(screen, rect);
CGContextDrawImage(screen, rect, img);
但是发生了一些奇怪的事情,当我提供的颜色为绿色时,我可以看到黑色线条。 以下是创建位图上下文后的代码:
CGFloat black[4] = {0.0f,1.0f,0.0f,1.0f}; //RGB values
CGContextSetStrokeColor(c, black);
这似乎是代码适用的唯一组合...
有人知道吗?
【问题讨论】:
标签: iphone objective-c bitmap