iphone - 如何为 CGPoint 线赋予独特的颜色 Xcode

标签 iphone objective-c xcode cgpoint

一个非常简单的 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

最佳答案

在通过 linesInProcess 循环的 drawRect 中,您没有设置颜色。您需要使用线条对象中的颜色信息并在每次循环迭代中重置颜色:

CGContextSetStrokeColorWithColor(context, line.COLOUR.CGColor);

或者,或者

[line.COLOUR set];

这同样适用于您的 completeLines 循环。

PS:您可以为类的属性使用通常的驼峰式变量名称,这对您自己有好处。

关于iphone - 如何为 CGPoint 线赋予独特的颜色 Xcode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13864459/

相关文章:

iphone - Iphone 的 UIPOPOVER?还是假的?

iphone - 如何避免在设备旋转时将 ImageView 更改为旋转

iOS Enterprise OTA - 有没有办法从 php 输出 plist?

iphone - 从 iPad/iPhone 连接到 Airport Extreme 上的文件共享

ios - 为什么 NSDateFormatter 在 iOS 7 上返回 nil

iphone - UIView 意外进入状态栏下方

ios - 解析嵌套的 JSON SWIFT 4

ios - 将 Storyboard从 iPhone 转换为 iPad

iphone - UILocalNotification 的警报 Action 代码

ios - 从其中一个末端同时旋转 y,z 轴上的 View