2010-10-18 15 views
6

Sto cercando di implementare una vista di disegno molto semplice nella mia app. Questa è solo una piccola parte della mia app, ma si sta trasformando in una vera seccatura. Questo è quello che ho finora, ma tutto ciò che sta visualizzando adesso è il codice morse come punti e linee.iPad (molto) semplice disegno

- (void)viewDidLoad { 
     [super viewDidLoad]; 
    self.view.backgroundColor = [UIColor whiteColor]; 
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
                 NSUserDomainMask, YES); 
    NSString *docsPath = [paths objectAtIndex:0]; 

    NSString *savePath = [NSString stringWithFormat:@"%@/notePadImage.jpg",docsPath]; 

    NSData *data = [NSData dataWithContentsOfFile:savePath]; 

    UIImage *image = [UIImage imageWithData:data]; 

    if (image == nil) { 
     NSString *pathToBlank = [[NSBundle mainBundle]pathForResource:@"blankNotePadPage" ofType:@"png"]; 
     NSData *data = [NSData dataWithContentsOfFile:pathToBlank]; 
     image = [UIImage imageWithData:data]; 
    } 
    arrayOfTouches = [[NSMutableArray alloc] initWithCapacity:10]; 
    self.drawImage.image = image; 

    mouseMoved = 0; 
    [self.view bringSubviewToFront:closeButton]; 
    [self.view bringSubviewToFront:clearButton]; 
    self.timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(drawIt) userInfo:nil repeats:YES]; 

    } 

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 


    UITouch *touch = [touches anyObject]; 

    [arrayOfTouches addObject:touch]; 




    } 


    - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { 

    UITouch *touch = [touches anyObject]; 
    [arrayOfTouches addObject:touch]; 


    } 

    - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { 

    } 

    -(void) drawIt { 

    NSMutableArray *tempArray = [NSMutableArray arrayWithArray:arrayOfTouches]; 
    [arrayOfTouches removeAllObjects]; 
    if ([tempArray count]>1) { 

     [arrayOfTouches removeAllObjects]; 
     CGPoint point1 = [[tempArray objectAtIndex:0] previousLocationInView:self.view];; 
     CGPoint point2; 
     CGPoint point3; 

     for (int i = 0; i < [tempArray count]-1;i = i+1) { 




      UIGraphicsBeginImageContext(self.view.frame.size); 
      [drawImage.image drawInRect:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)]; 
      CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound); 
      CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 3.0); 
      CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.0, 0.0, 0.0, 1.0); 
      CGContextMoveToPoint(UIGraphicsGetCurrentContext(), point1.x, point1.y); 
      CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), point2.x, point2.y); 

      CGContextStrokePath(UIGraphicsGetCurrentContext()); 
      CGContextFlush(UIGraphicsGetCurrentContext()); 
      drawImage.image = UIGraphicsGetImageFromCurrentImageContext(); 
      UIGraphicsEndImageContext(); 
      [self.view bringSubviewToFront:closeButton]; 
      [self.view bringSubviewToFront:clearButton]; 
      point1 = point2; 

     } 

     } 
    } 

risposta

10

Una delle mie app aveva anche bisogno di un semplice disegno. Ecco una versione leggermente modificata di esso. Funziona fondamentalmente come descritto da hotpaw2. Ho creato una vista "tela" che gestisce tutto il disegno e la aggiungo ovunque sia necessario.

La velocità va bene per i miei scopi.

CanvasView.h:

@interface CanvasView : UIView { 
    NSMutableArray *points; 
} 
@property (nonatomic, retain) NSMutableArray *points; 
@end 

CanvasView.m:

#import "CanvasView.h" 

@implementation CanvasView 

@synthesize points; 

- (id) initWithFrame:(CGRect)frame { 
    if (self = [super initWithFrame:frame]) { 
     self.backgroundColor = [UIColor blueColor]; 
    } 
    return self; 
} 

-(void)drawRect:(CGRect)rect 
{ 
    if (self.points.count == 0) 
     return; 

    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0); //white 
    CGContextSetLineWidth(context, 1.0); 

    CGPoint firstPoint = [[self.points objectAtIndex:0] CGPointValue]; 
    CGContextBeginPath(context); 
    CGContextMoveToPoint(context, firstPoint.x, firstPoint.y); 

    int i = 1; 
    while (i < self.points.count) 
    { 
     CGPoint nextPoint = [[self.points objectAtIndex:i] CGPointValue]; 

     if (nextPoint.x < 0 && nextPoint.y < 0) 
     { 
      CGContextDrawPath(context, kCGPathStroke); 

      if (i < (self.points.count-1)) 
      { 
       CGContextBeginPath(context); 
       CGPoint nextPoint2 = [[self.points objectAtIndex:i+1] CGPointValue];     
       CGContextMoveToPoint(context, nextPoint2.x, nextPoint2.y); 
       i = i + 2; 
      } 
      else 
       i++; 
     } 
     else 
     { 
      CGContextAddLineToPoint(context, nextPoint.x, nextPoint.y); 
      i++; 
     } 
    } 

    CGContextDrawPath(context, kCGPathStroke); 
} 

-(void)dealloc 
{ 
    [points release]; 
    [super dealloc]; 
} 

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *touch = [[event touchesForView:self] anyObject]; 
    CGPoint location = [touch locationInView:self]; 

    if (self.points == nil) 
    { 
     NSMutableArray *newPoints = [[NSMutableArray alloc] init]; 
     self.points = newPoints; 
     [newPoints release]; 
    } 

    [self.points addObject:[NSValue valueWithCGPoint:(location)]]; 
} 

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *touch = [[event touchesForView:self] anyObject]; 
    CGPoint location = [touch locationInView:self]; 
    [self.points addObject:[NSValue valueWithCGPoint:(location)]]; 

    [self setNeedsDisplay]; 
} 

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *touch = [[event touchesForView:self] anyObject]; 
    CGPoint location = [touch locationInView:self]; 
    [self.points addObject:[NSValue valueWithCGPoint:(location)]]; 

    CGPoint endPoint = CGPointMake(-99, -99); //"end of path" indicator 
    [self.points addObject:[NSValue valueWithCGPoint:(endPoint)]]; 

    [self setNeedsDisplay]; 
} 

@end 

Aggiunta del canvasView dove è necessario:

CanvasView *cv = [[CanvasView alloc] initWithFrame:CGRectMake(0, 0, 320, 640)]; 
[self.view addSubview:cv]; 
[cv release]; 
+0

questa è esattamente la cosa che stavo cercando, grazie. – Brodie

+0

come potrei salvare ciò che viene disegnato qui come jpg? – Slee

+1

'UIGraphicsBeginImageContext (cv.bounds.size); [cv.layer renderInContext: UIGraphicsGetCurrentContext()]; UIImage * image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); NSData * data = UIImageJPEGRepresentation (image, 1.0f); NSString * path = ...; BOOL salvato = [data writeToFile: path atomically: YES]; ' – Anna

4

Non disegnare mentre si maneggiano i tocchi. Rallenterà il gestore del tocco così tanto che potresti ottenere l'effetto "connetti i punti" che stai vedendo.

Salvare le coordinate di tocco in un array e pianificare di disegnarle in un secondo momento.

Guarda alcuni semplici tutorial di animazione su come disegnare in un drawRect basato su un setNeedsDisplay chiamato da un'animazione UITimer o CADisplayLink. Disegna tutti i tuoi segmenti di linea lì a un ritmo più adatto.

+0

grazie per il commento - ho cercato per i tutorial e non riusciva a trovare nulla . Ne ho trovato uno che si occupa di disegnare un cerchio, quindi sono stato in grado di iniziare ma questo è tutto. Quindi, quello che devo fare è mantenere una serie di CGPoints tenuti come NSValues, quindi fare in modo che un timer colleghi i punti ogni 1/4 di secondo o qualcosa del genere? – Brodie

Problemi correlati