gpt4 book ai didi

ios - MotionBegan、setStroke 和 drawRect 的正确用法

转载 作者:行者123 更新时间:2023-11-29 03:48:03 29 4
gpt4 key购买 nike

我正在解决 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

最佳答案

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

关于ios - MotionBegan、setStroke 和 drawRect 的正确用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17454829/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com