Could anyone explain drawrect and context animation?

220 views Asked by At

I'm quitely new for the iOS, so I don't know much of it. I know how to make UIView (and its childviews) but I don't know about drawRect

I make a class which inherits from UIView and make subviews in initWithFrame method. I want to draw a NSString using CGContext after adding subViews and move it outside of view after 5 seconds.

Could anyone explain when drawRect is called and how to move it?

2

There are 2 answers

2
user1118321 On

One way to do it would be to draw the string and then start an NSTimer. Start a 5 second timer, and when it fires, then you can move it.

As for when -drawRect: is called - it's called whenever your view needs to be updated. It will be called when your view is first displayed by the OS. After that, it will usually be called when it changes size or shape, or when your code calls [myView setNeedsDisplay:YES], which tells the OS to update it.

0
Alex Cio On

This code helps you to draw a NSString which was stored before in _content:

- (void)drawRect:(CGRect)rect{

    CGContextRef context = UIGraphicsGetCurrentContext();
    [_content drawInRect:rectForFrame
                withFont:[UIFont fontWithName:kFontMedium size:15.0f]
           lineBreakMode:NSLineBreakByWordWrapping
               alignment:NSTextAlignmentCenter];
}

To let the element slide out, you would have to call a NSTimer after your UIView was shown (Maybe with a delay using performSelector:withObject:afterDelay:) and change the attributes of the CGRect you want to write the NSString inside. You can just setup a method which will be called by your NSTimer in a specific interval which also updates the UIView.

- (void)updateView{

  //create a rect
  rectForFrame = CGRectMake....;
  [self setNeedsDisplay];
}