简体   繁体   中英

Get the Context of UIView without using drawrect Method

I need to draw on my uiview without using the drawrect method but i don't know how to get the graphics context dynamically at any point of time?

For example: I need to add a line when user selected the add line from from pop over in my toolbar.

This can't be done. You will have to have some kind of marker to indicate a new line and then call setNeedsDisplay method so that it invokes the drawRect: method. You can check for the marker in the drawRect: method and draw the line accordingly.

You will have to save state. Probably an array of lines added so that you can use it to draw the view when drawRect: method is invoked.

An alternative

You can use an image view for this purpose. You can do this,

UIGraphicsBeginImageContext(imageView.frame.size);
[imageView.image drawInRect:CGRectMake(0, 0, imageView.frame.size.width, imageView.frame.size.height)];
/* Draw line here */
imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

This way you won't have state but you simply add the line to the image.

Your view has no graphics context outside of drawRect: . You cannot make arbitrary drawing calls outside of drawRect: and have them persist.

If you need to dynamically add lines etc. to a view, you must first store the lines in an array or other structure, and then iterate that structure inside drawRect: and draw each item.

Alternatively, make each line a custom view itself (or a layer) and add it as a subview.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM