0

我正在解决 Big Nerd Ranch 的 iOS 编程指南中关于 UIView 子类化的一章中的挑战。

我在下面有一些代码以随机颜色绘制同心圆。而且,在摇晃时,它应该将它们全部变为红色。这不是因为在设置了红色之后,再次调用了drawRect并重做了随机颜色循环。

实现这一点的正确方法是将随机颜色循环移出drawRect的某个地方吗?我是否设置了一个信号量(混乱)以确保循环只运行一次?

谢谢你的建议。

- (void)setCircleColor:(UIColor *)clr
{
    circleColor = clr;
    [self setNeedsDisplay];
}

- (BOOL) canBecomeFirstResponder
{
    return YES;
}

- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    if (motion == UIEventSubtypeMotionShake) {
        [self setCircleColor:[UIColor redColor]];
    }
}

-(void)drawRect:(CGRect)dirtyRect
{
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGRect bounds = [self bounds];

    // Figure out the center of the bounds rectangle
    CGPoint center;
    center.x = bounds.origin.x + bounds.size.width / 2.0;
    center.y = bounds.origin.y + bounds.size.height / 2.0;

    float maxRadius = hypot(bounds.size.width, bounds.size.height) / 2.0;

    CGContextSetLineWidth(ctx, 10);

    // Set up an array of colors
    UIColor *red = [UIColor redColor];
    UIColor *green = [UIColor greenColor];
    UIColor *yellow = [UIColor yellowColor];

    NSArray *colors = [[NSArray alloc]initWithObjects:red, green, yellow, nil];

    // Draw concentric circles from the outside in

    for (float currentRadius = maxRadius; currentRadius > 0; currentRadius -= 20) {
        CGContextAddArc(ctx, center.x, center.y, currentRadius, 0.0, M_PI * 2, YES);

        // Random index for colors array
        NSUInteger randomIndex = arc4random() % [colors count];
        [self setCircleColor:[colors objectAtIndex:randomIndex]];

        [[self circleColor] setStroke];

        // Perform drawing; remove path
        CGContextStrokePath(ctx);
    }

    NSString *text = @"You are getting sleepy.";
    UIFont *font = [UIFont boldSystemFontOfSize:28];

    CGRect textRect;

    textRect.size = [text sizeWithFont:font];

    // Let's put that string in the center of the view
    textRect.origin.x = center.x - textRect.size.width / 2.0;
    textRect.origin.y = center.y - textRect.size.height / 2.0;

    [[UIColor blackColor] setFill];

    // Draw a shadow
    CGSize offset = CGSizeMake(4, 3);
    CGColorRef color = [[UIColor darkGrayColor] CGColor];
    CGContextSetShadowWithColor(ctx, offset, 2.0, color);

    [text drawInRect:textRect withFont:font];



}

-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setBackgroundColor:[UIColor clearColor]];
        [self setCircleColor:[UIColor lightGrayColor]];
    }
    return self;
}
@end
4

1 回答 1

1

摇动设备后制作一个BOOL isSHake并取消随机颜色,圆圈将保持红色,您可以在其他操作时将其重置。

于 2013-07-03T18:28:05.740 回答