Posted By

devb0yax on 07/13/10


Tagged

iphone


Versions (?)

draw2


 / Published in: iPhone
 

  1. DrawView.h
  2. #import <UIKit/UIKit.h>
  3.  
  4.  
  5. @interface DrawView : UIView {
  6. NSMutableArray *points;
  7. }
  8. @property (retain) NSMutableArray *points;
  9. @end
  10.  
  11. ----------------------
  12. .m file:
  13. #import "DrawView.h"
  14.  
  15. #define POINT(X) [[self.points objectAtIndex:X] CGPointValue]
  16.  
  17. UIColor *current;
  18.  
  19. @implementation DrawView
  20.  
  21. @synthesize points;
  22.  
  23. - (id)initWithFrame:(CGRect)frame {
  24. if ((self = [super initWithFrame:frame])) {
  25. // Initialization code
  26. current = [UIColor whiteColor];
  27. }
  28. return self;
  29. }
  30.  
  31. - (void)drawRect:(CGRect)rect {
  32. // Drawing code
  33. if (!self.points) return;
  34. if (self.points.count < 2) return;
  35.  
  36. CGContextRef context = UIGraphicsGetCurrentContext();
  37. [current set];
  38. CGContextSetLineWidth(context, 4.0f);
  39.  
  40. for (int i = 0; i < (self.points.count - 1); i++)
  41. {
  42. CGPoint pt1 = POINT(i);
  43. CGPoint pt2 = POINT(i+1);
  44. CGContextMoveToPoint(context, pt1.x, pt1.y);
  45. CGContextAddLineToPoint(context, pt2.x, pt2.y);
  46. CGContextStrokePath(context);
  47. }
  48.  
  49. }
  50.  
  51. - (void)dealloc {
  52. [super dealloc];
  53. }
  54.  
  55. #pragma mark -
  56. #pragma mark UI Touches
  57. #pragma mark -
  58. - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
  59. {
  60. self.points = [NSMutableArray array];
  61. CGPoint pt = [[touches anyObject] locationInView:self];
  62. [self.points addObject:[NSValue valueWithCGPoint:pt]];
  63. }
  64.  
  65. - (void) touchesMoved:(NSSet *) touches withEvent:(UIEvent *) event
  66. {
  67. CGPoint pt = [[touches anyObject] locationInView:self];
  68. [self.points addObject:[NSValue valueWithCGPoint:pt]];
  69. [self setNeedsDisplay];
  70. }
  71.  
  72. @end
  73.  
  74. ==========================
  75. DrawViewController.m
  76. ....
  77. - (void)viewDidLoad {
  78. [super viewDidLoad];
  79.  
  80. DrawView *tv = [[DrawView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 240.0f, 240.0f)];
  81. tv.center = CGPointMake(160.0f, 140.0f);
  82. [self.view addSubview:tv];
  83. [tv release];
  84. }

Report this snippet  

You need to login to post a comment.