-->

Draw a line over UIViewController

2020-07-31 19:45发布

问题:

I have my app on iPhone with a UIViewController with some stuff inside.. image, textbox, etc... is there a way to draw a line or something like this using opengl directly inside the UIViewController?

thanks in advance

回答1:

Are you sure about the OpenGL?

I believe it will be impossible to use OpenGL above regular views.

You might add a custom view (inherit from UIView) above all the other views and draw anything you want on that view.
This view should have a transparent background color.
In addition, if you want to interact with the other views (tap buttons, edit text views, scroll etc.) then you will have to implement the hitTest method in your custom view in order to pass the touch event to the views that are located under this one...

EDIT: Don't mess with the hitTest. Just uncheck the User Interaction Enabled in the XIB...

EDIT: Code sample:

@interface TransparentDrawingView : UIView {
    CGPoint fromPoint;
    CGPoint toPoint;
}
- (void)drawLineFrom:(CGPoint)from to:(CGPoint)to;
@end

@implementation TransparentDrawingView

- (void)initObject {
    // Initialization code
    [super setBackgroundColor:[UIColor clearColor]];
}
- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        // Initialization code
        [self initObject];
    }
    return self;
}
- (id)initWithCoder:(NSCoder *)aCoder {
    if (self = [super initWithCoder:aCoder]) {
        // Initialization code
        [self initObject];
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    // Drawing code

    // Draw a line from 'fromPoint' to 'toPoint'
}
- (void)drawLineFrom:(CGPoint)from to:(CGPoint)to {
    fromPoint = from;
    toPoint = to;

    // Refresh
    [self setNeedsDisplay];
}

@end


回答2:

First I think you should know responsibilities of UIView and UIViewController. UIView is mainly responsible for drawing (override touchBegin, ToucheMove, etc.), animating, manage subviews, and handle event; UIViewController is mainly responsible for loading, unloading views etc.

So, you should 'draw' this line at your customized view (UIView), not view controller.

Second: If you only need to display some simple shapes or lines. I suggest you use UI controls and images. Even 'drawRect' is not recommended since it will cause more resources used. Surely OpenGL need much resources.



回答3:

The answer is quite simple, you have to create a new class extending UIView, and override the drawRect function in order to draw (with Quartz...) your line. Use this method if you want gradient background as well.

I am also developping with Adobe Flex 4, and I notice that iPhone SDK has no Skin and Layout "patterns" like Flex 4 does (for instance, UIView could have a Skin (in a separate file..) and a Layout (horizontal, Vertical, Tile....)), for me that is a terrible lack!

Its something that the open source library Three20 tries to bring to the iPhone SDK.