2

I'm looking for a "canvas-like" element to use in iOS apps. By "canvas-like" I mean that I want a surface on which I can draw basic shapes such as rectangles, lines, text, or images. I do not need 3D or other really advanced stuff -- rectangles and other images would be enough, text can be stored in images if required.

I can't imagine that no such API is available, but how do they call it?

jscs
  • 63,694
  • 13
  • 151
  • 195
friedkiwi
  • 2,158
  • 8
  • 29
  • 52
  • See http://stackoverflow.com/questions/6724800/how-to-use-drawrect-to-draw-in-a-existing-view/6725315#6725315 – Rob Napier Oct 30 '11 at 20:26

2 Answers2

3

With UIKit, everything that the user sees and interacts with is essentially a view. For instance, a button is a view, a table view is a view, etc. Your application should already have a main view controller, or a main window, which can contain zero or more views. You can draw on any view that you create, as long as you are in the position to implement the drawRect: method. Here's an example of implementing a UIView subclass on which can you can draw using CoreGraphics:

@interface MyView : UIView
@end

@implementation MyView

- (void)drawRect:(CGRect)dirtyRect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBFillColor(context, 0, 0, 0, 1);
    // here, you can draw shapes, for example, a circle:
    CGContextFillEllipseInRect(context, CGContextMake(10, 10, 50, 50));
}

@end

Then, in order to add an instance of MyView to your application, either drag in a custom view in interface builder and change its class to MyView, or do this in viewDidLoad of your view controller:

- (void)viewDidLoad {
    MyView * aView = [[MyView alloc] initWithFrame:self.bounds];
    [self.view addSubview:aView];
#if __has_feautre(objc_arc) != 1
    [aView release];
#endif
}

You can learn more about what you can do in the drawRect method from the Quartz 2D Programming Guide.

Alex Nichol
  • 7,512
  • 4
  • 32
  • 30
0

Canvas like the HTML 5 <canvas>? Check "Core Graphics" (a.k.a. Quartz 2D).

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005