简体   繁体   English

自定义UIView drawRect动画

[英]Custom UIView drawRect Animation

I am making a custom UIView subclass that draws a graph (in my own drawRect method) and responds to touch events. 我正在制作一个自定义UIView子类,该子类绘制一个图形(在我自己的drawRect方法中)并响应触摸事件。 I need to have various parts of the graph animate (like blinking hotspots or decelerating a pan after a touch event). 我需要使图表的各个部分动画(例如,闪烁的热点或在触摸事件后使平移减速)。

The parameters that drive animation are entirely private to my view, and I would ideally like to keep these behaviors encapsulated in the class. 驱动动画的参数对我来说是完全私有的,并且理想情况下,我希望将这些行为封装在类中。 Ie I don't want the view that hosts this view to have to do anything to make this work. 即,我不希望承载此视图的视图必须做任何事情才能使此工作正常进行。 My view knows how often it needs to redraw and I'd like it to be in control of that. 我的观点知道它需要多久重绘一次,我希望它能够对此进行控制。

My intuition would be to create a timer in my view class for running my animations, but I'm having trouble getting it to fire and I'm getting an impression that's not the best practice here. 我的直觉是在我的视图类中创建一个计时器来运行动画,但是我很难使其启动,并且给人的印象不是这里的最佳实践。

What I need is a way for my view to request that its drawRect get called periodically and ideally be able to control that period dynamically (so I can slow it down when less stuff is happening). 我需要的是一种可以定期调用其drawRect的视图的方法,理想情况下,它可以动态控制该时间段(这样,当发生较少的事情时,我可以将其放慢)。

I've looked at some of the CoreAnimation approaches and they look overkill to me, though I'm willing to plunge in to that if it's the right approach. 我已经看过一些CoreAnimation方法,但对我来说它们看起来有些过激,尽管如果这种方法正确,我愿意尝试。

Is there a simple way for me to get my view's drawRect method to be called on a regular basis? 我有一种简单的方法可以定期调用视图的drawRect方法吗? Can I control how often it happens? 我可以控制它发生的频率吗?

you shouldn't call drawRect directly.Instead call setNeedsDisplay , which calls drawRect. 您不应直接调用drawRect,而应调用setNeedsDisplay来调用drawRect。

Change few parameters in drawRect and call setneedsdisplay, it will render your view one more time. 在drawRect中更改一些参数并调用setneedsdisplay,它将使您的视图再显示一次。

But call to drawRect very frequently will impact the performance of your app.Apple even recommends to follow CAAnimations -core animations to do animations not to call drawRect for animation. 但是频繁调用drawRect会影响应用程序的性能.Apple甚至建议遵循CAAnimations -core动画来制作动画,而不要为drawRect调用动画。

Santhu's comment answers my question best. Santhu的评论最能回答我的问题。

For very simple animations, I am able to use this mechanism to get my view refreshed periodically: 对于非常简单的动画,我可以使用此机制来定期刷新视图:

[self performSelector:@selector(setNeedsDisplay) withObject:nil afterDelay:2.0];

I think for more complex things, I would dive into the CoreAnimation stuff, which I'm sure is less complex than it seems at first blush. 我认为,对于更复杂的事情,我将深入研究CoreAnimation的内容,我相信它比起初看起来不太复杂。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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