一个非常简单的 XCode iPhone 应用程序。空白屏幕,画线,每条线都有一个通过随机数生成的唯一颜色。我有代码给我随机颜色,但我无法让线条单独保留颜色。每次绘制屏幕时,我的数组中所有行的颜色都会发生变化。
这是为每一行设置颜色的代码:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
for (UITouch *t in touches) {
// Is this a double-tap?
if ([t tapCount] > 1) {
[self clearAll];
return;
}
CGFloat hue = ( arc4random() % 256 / 256.0 ); // 0.0 to 1.0
CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0, away from white
CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0, away from black
Colour=[UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
// Use the touch object (packed in an NSValue) as the key
NSValue *key = [NSValue valueWithPointer:t];
// Create a line for the value
CGPoint loc = [t locationInView:self];
Line *newLine = [[Line alloc] init];
[newLine setBegin:loc];
[newLine setEnd:loc];
[newLine setCOLOUR:Colour];
// Put pair in dictionary
[linesInProcess setObject:newLine forKey:key];
[newLine release];
}
}
这是我用来画线的代码。
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 10.0);
CGContextSetLineCap(context, kCGLineCapRound);
for (Line *line in completeLines) {
[Colour set];
CGContextMoveToPoint(context, [line begin].x, [line begin].y);
CGContextAddLineToPoint(context, [line end].x, [line end].y);
CGContextStrokePath(context);
}
// Draw lines in process in red
[[UIColor redColor] set];
for (NSValue *v in linesInProcess) {
Line *line = [linesInProcess objectForKey:v];
CGContextMoveToPoint(context, [line begin].x, [line begin].y);
CGContextAddLineToPoint(context, [line end].x, [line end].y);
CGContextStrokePath(context);
}
}
重申一下:我试图为界面上绘制的每条线赋予独特的颜色。所述颜色由随机数 gen 给出。
感谢帮助,人们。:D