vrwim vrwim - 24 days ago 13
iOS Question

Draw on UIView or GLKView?

I need to draw a separator line with some dots on it. I have decided I will do this using the draw method, as opposed to including images of the separator. I will do this for performance and for customisability, as the separator changes sometimes.

Now I have looked into the

draw()
method on
UIView
and I have noticed that Apple suggests using
GLKView
when drawing using OpenGL.

For a simple separator, won't it be too much of a hassle to call OpenGL? Or is the OpenGL overhead negligible? When would I want to use the native UIKit
draw()
then?

FYI I don't know either method, but want to learn both methods, so don't reply "what you know best". I am simply asking about performance.

Answer

OpenGL uses GPU instead of CPU for computation. If you are making something like a gaming app, then you can think of using OpenGL. I believe you want to draw a line in an iOS App. For that you can either use drawRect method in UIView or create a shapeLayer and add it as a sublayer.

The following examples will show you:

CAShapeLayer *simpleLine = [CAShapeLayer layer];
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(0, 80)];
[path addLineToPoint:CGPointMake(300, 80)];
simpleLine.lineWidth = 1.0;
simpleLine.path = path.CGPath;
simpleLine.strokeColor = [[UIColor blackColor] CGColor];
[[self.view layer] addSublayer:simpleLine];

For using drawRect, you are supposed to do this inside a Custom UIView as opposed to the above method.

- (void)drawRect:(CGRect)rect {
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(0, 80)];
    [path addLineToPoint:CGPointMake(300, 80)];
    path.lineWidth = 1.0;
    [[UIColor blueColor] setStroke];
    [path stroke];
}

If your separator parameters changes and if you are making an app, it's better to use drawRect method. You can call this method anytime by using [CustomUIView setNeedsDisplay:YES]

Edit

What you're asking for is circle over line. You can do that by drawing UIBezierPath for line first and then add UIBezierPath for circle later.