2

How to Subclass UIView and then how to use it with drawRect to draw graphics? Do I need to add the framework and then include in the header file QuartzCore or any other?


Combined solutions:


#import <UIKit/UIKit.h>
@interface drawingViewController : UIViewController {
}
@end

#import "drawingViewController.h"
#import "myview.h"
@implementation drawingViewController
- (void)viewDidLoad {
    [super viewDidLoad];

    CGRect rect = CGRectMake(0,0,340,480);  
    myview *ui = [[myview alloc] initWithFrame:rect];
    [self.view addSubview:ui];
}

#import <UIKit/UIKit.h>
@interface myview : UIView {
}
@end

#import "myview.h"
@implementation myview
- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code.
    }
    return self;
}


// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code.
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextAddArc(context, 50, 50, 50, 0, 30, 0);
CGContextFillPath(context);

    //set the fill or stroke color
    CGContextSetRGBFillColor(context, 1, 0.5, 0.5, 1.0);
    CGContextSetRGBStrokeColor(context, 0.5, 1, 0.5, 1.0);

    //fill or draw the path
    CGContextDrawPath(context, kCGPathStroke);
    CGContextDrawPath(context, kCGPathFill);

    ------------------------------
    CGContextAddArc(context, 100, 100, 20, 0, 30, 0);

    //set the fill or stroke color
    CGContextSetRGBFillColor(context, 1, 0.5, 0.5, 1.0);
    CGContextSetRGBStrokeColor(context, 0.5, 1, 0.5, 1.0);

    //fill or draw the path
    CGContextDrawPath(context, kCGPathStroke);
    CGContextDrawPath(context, kCGPathFill);

}

other things to note:

Drawing triangle/arrow on a line with CGContext

CGContext Optimization

iPhone clear CGContext

Saving and restoring CGContext

How do I draw a line on the iPhone?

How to draw string in other device orientations using CGContext iOS

Community
  • 1
  • 1
jdl
  • 6,151
  • 19
  • 83
  • 132

1 Answers1

0

in .h file

#import <QuartzCore/QuartzCore.h>
@interface YourView : UIView {

...

in .m file

- (void)drawRect:(CGRect)rect{
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    //your drawings
}

then call setNeedsDisplay to redraw the rect

frx08
  • 4,222
  • 8
  • 37
  • 45