ProCoreData / chapter5 / Shapes / Shapes / BasicCanvasUIView.m

//  BasicCanvasUIView.m
//  Shapes
//  Created by han pyanfield on 11-12-8.
//  Copyright (c) 2011年 pyanfield. All rights reserved.

#import "BasicCanvasUIView.h"

@implementation BasicCanvasUIView

@synthesize canvas = _canvas;

- (float)scale
    NSManagedObject *transform = [self.canvas valueForKey:@"transform"];
    return [[transform valueForKey:@"scale"] floatValue];

//p153 override the drawRect method to redraw the view content.
- (void)drawRect:(CGRect)rect
    NSLog(@">> BasicCanvasUIView drawRect");
    if (self.canvas == nil) {
    CGContextRef context = UIGraphicsGetCurrentContext();
    float scale = self.scale;
    CGContextScaleCTM(context, scale, scale);
    //retrieve al the shapes that relate to this canvas and iterate through them
    NSSet *shapes = [self.canvas valueForKey:@"shapes"];
    for (NSManagedObject *shape in shapes) {
        NSString *entityName = [[shape entity] name];
        NSString *colorCode = [shape valueForKey:@"color"];
        NSArray *colorCodes = [colorCode componentsSeparatedByString:@","];
        CGContextSetRGBFillColor(context, [[colorCodes objectAtIndex:0] floatValue]/255,[[colorCodes objectAtIndex:1] floatValue]/255,[[colorCodes objectAtIndex:2] floatValue]/255,1.0);
        //if this shape is Circle
        if ([entityName compare:@"Circle"] == NSOrderedSame) {
            float x = [[shape valueForKey:@"x"] floatValue];
            float y = [[shape valueForKey:@"y"] floatValue];
            float radius = [[shape valueForKey:@"radius"] floatValue];
            CGContextFillEllipseInRect(context, CGRectMake(x-radius, y-radius, 2*radius, 2*radius));
        }else if([entityName compare:@"Polygon"] == NSOrderedSame)
            NSSortDescriptor *sortDesciptor = [[NSSortDescriptor alloc] initWithKey:@"index" ascending:YES];
            NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDesciptor,nil];
            NSArray *vertices = [[[shape mutableSetValueForKey:@"vertices"] allObjects] sortedArrayUsingDescriptors:sortDescriptors];
            // begin drawing the polygon
            NSManagedObject *lastVertex = [vertices lastObject];
            CGContextMoveToPoint(context, [[lastVertex valueForKey:@"x"] floatValue], [[lastVertex valueForKey:@"y"] floatValue]);
            for(NSManagedObject *vertext in vertices){
                CGContextAddLineToPoint(context, [[vertext valueForKey:@"x"] floatValue], [[vertext valueForKey:@"y"] floatValue]);