我正在尝试修改一些简单的"创建绘画应用程序"代码,使其背景颜色为白色,而不是设置为黑色。示例代码位于:
http://blog.effectiveui.com/?p=8105
我尝试过设置self.backgroundcolor=[UIColor whiteColor],也尝试过设置[[UIColor whiteColor]setFill],但没有效果。由于我缺乏经验,我错过了一些基本的东西。
有人有什么想法吗?非常感谢!
我在drawRect中添加了几行,应该可以为您完成此操作。你在正确的轨道上,但当你将颜色设置为白色时,你实际上需要用它填充paintView矩形:
- (void)drawRect:(CGRect)rect {
if(touch != nil){
CGContextRef context = UIGraphicsGetCurrentContext();
//clear background color to white
[[UIColor whiteColor] setFill];
CGContextFillRect(context, rect);
hue += 0.005;
if(hue > 1.0) hue = 0.0;
UIColor *color = [UIColor colorWithHue:hue saturation:0.7 brightness:1.0 alpha:1.0];
CGContextSetStrokeColorWithColor(context, [color CGColor]);
CGContextSetLineCap(context, kCGLineCapRound);
CGContextSetLineWidth(context, 15);
CGPoint lastPoint = [touch previousLocationInView:self];
CGPoint newPoint = [touch locationInView:self];
CGContextMoveToPoint(context, lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(context, newPoint.x, newPoint.y);
CGContextStrokePath(context);
}
}
原因view.backgroundColor=[UIColor whiteColor];不起作用的是,任何实现drawRect的视图都会忽略backgroundColor属性,程序员负责绘制整个视图内容,包括背景。
我想你错过的部分是PaintView:的这一部分
- (BOOL) initContext:(CGSize)size {
int bitmapByteCount;
int bitmapBytesPerRow;
// Declare the number of bytes per row. Each pixel in the bitmap in this
// example is represented by 4 bytes; 8 bits each of red, green, blue, and
// alpha.
bitmapBytesPerRow = (size.width * 4);
bitmapByteCount = (bitmapBytesPerRow * size.height);
// Allocate memory for image data. This is the destination in memory
// where any drawing to the bitmap context will be rendered.
cacheBitmap = malloc( bitmapByteCount );
if (cacheBitmap == NULL){
return NO;
}
cacheContext = CGBitmapContextCreate (cacheBitmap, size.width, size.height, 8, bitmapBytesPerRow, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaNoneSkipFirst);
return YES;
}
这创建了一个单独的上下文,它称之为缓存,所有后续的触摸都被绘制到该上下文中。在视图的drawRect:
中,它只是将缓存复制到输出中。
它提供的标志之一kCGImageAlphaNoneSkipFirst
指定缓存的上下文没有alpha通道。因此,当它被绘制出来时,无论其他因素如何,背景都没有机会显示出来;黑色来自cacheContext,就像你用手指画黑色一样。
因此,您真正想做的是在开始之前用白色填充cacheContext。您可以通过memsetting cacheBitmap数组来实现这一点,因为您已经明确地告诉上下文将其数据存储在哪里,或者您可以对cacheContext使用合适的CGContextFillRect
。
如果你想使用源代码,但要创建并"墨迹"的图像有一个清晰的背景,那么当你设置cachedBitmap时,就这样做。
cacheContext = CGBitmapContextCreate ( cacheBitmap
, size.width
, size.height
, 8
, bitmapBytesPerRow
, CGColorSpaceCreateDeviceRGB()
, kCGImageAlphaPremultipliedFirst
);
这样,当您为"墨迹"设置笔划颜色时,只会绘制"墨迹"。确保工程视图的背景色也为clearColor,不透明设置为NO。
这意味着,已添加工程视图的视图现在将在该工程视图下方或通过该工程视图可见。因此,将该视图的背景色设置为您想要的任何颜色,或者,在工程视图后面放一个UIImageView,瞧!你可以插入一个图像的衬纸或图形纸或任何你想要的!