Chapter 5 带颜色的同心圆

一、重写 DrwaRect

-(void)drawRect:(CGRect)rect
{
    CGRect bounds = self.bounds;
    
    CGPoint center;
    center.x = bounds.origin.x + bounds.size.width / 2.0;
    center.y = bounds.origin.y + bounds.size.height / 2.0;
    
    float maxRadius = MAX(bounds.size.width, bounds.size.height);
    
  // 画圆 UIBezierPath
*path = [[UIBezierPath alloc] init]; for(float currentRadius = maxRadius; currentRadius > 0; currentRadius -= 20) { [path moveToPoint:CGPointMake(center.x + currentRadius, center.y)]; [path addArcWithCenter:center radius:currentRadius startAngle:0.0 endAngle:M_PI * 2.0 clockwise:YES]; } path.lineWidth = 10; // Configure the drawing color of light gray [self.circleColor setStroke]; [path stroke]; /* CGContextRef currentContext = UIGraphicsGetCurrentContext(); CGContextSaveGState(currentContext); [path addClip]; // Gradient triangle CGFloat location[2] = {0.0, 1.0}; CGFloat components[8] = {1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0}; CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB(); CGGradientRef gradient = CGGradientCreateWithColorComponents(colorspace, components, location, 2); CGPoint startPoint = CGPointMake(rect.size.width / 2.0, rect.size.height / 4.0); CGPoint endPoint = CGPointMake(rect.size.width / 2.0 , rect.size.height * 0.75); CGContextDrawLinearGradient(currentContext, gradient, startPoint, endPoint, 0); CGColorSpaceRelease(colorspace); CGGradientRelease(gradient); // Add shadow of image CGContextSetShadow(currentContext, CGSizeMake(4.0, 7.0), 3); // Draw stuff here, it will appear with a shadow // Add logo image UIImage *logoImage = [UIImage imageNamed:@"logo.png"]; CGRect logoRect = CGRectMake(rect.size.width / 4.0, rect.size.height / 4.0, rect.size.width/2.0, rect.size.height / 2.0); [logoImage drawInRect:logoRect]; CGContextRestoreGState(currentContext); // Draw stuff here, it will apear with no shadow; CGContextRelease(currentContext); */ }

二、重写 touchesBegin:withEvent 

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//    NSLog(@"%@ was touched", self);
    
    // Get 3 random numbers between 0 and 1
    float red = (arc4random() % 100) / 100.0;
    float blue = (arc4random() % 100) / 100.0;
    float green = (arc4random() % 100) / 100.0;
    
    UIColor *randomColor = [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
    self.circleColor = randomColor;
}

三、重绘 View

[self setNeedsDisplay];
原文地址:https://www.cnblogs.com/1oo1/p/3974747.html