[英]how to avoid overriding drawRect when clipping
At the moment i'm overriding drawRect
in a view in order to be able to clip a colored rectangle with a mask (using CGContextClipToMask
inside drawRect
). 目前,我在视图中覆盖了
drawRect
以便能够使用蒙版剪切彩色矩形(使用drawRect
内部的CGContextClipToMask
)。 Sometimes I change the color of this clipped rectangle. 有时,我会更改此裁剪矩形的颜色。 In this case
drawRect
gets called again, redrawing and clipping the rectangle with the new color. 在这种情况下,再次调用
drawRect
,使用新颜色重新绘制和剪切矩形。 Now I don't want to change the color at once, but animate this. 现在,我不想立即更改颜色,而是对此进行动画处理。 The problem is, that animations are not performed when overriding drawRect (drawRect only gets called one time and immediately).
问题是,重写drawRect时不执行动画(drawRect仅一次被调用一次)。
Is there a way to perform this animation, maybe by subclassing the view, so that I still override drawRect
in the superclass, but the animation is somehow performed through the subclass so that drawRect from the superclass gets performed multiple times during the animation? 有没有一种方法可以执行此动画,可能是通过子视图化的,这样我仍然可以覆盖超类中的
drawRect
,但是以某种方式通过子类执行动画,以便超类中的drawRect
在动画中执行多次?
Or is also possible not to override drawRect
at all, and still be able to clip this rectangle with the mask somehow? 或者也可能根本不覆盖
drawRect
,并且仍然能够以某种方式用蒙版剪切此矩形? drawRect
looks something like this: drawRect
看起来像这样:
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGImageRef maskImage = [[UIImage imageNamed:maskName] CGImage];
CGContextClipToMask(ctx, rect, maskImage);
CGContextSetFillColorWithColor(ctx, self.currentColor);
CGContextFillRect( ctx, rect );
One solution would be to have a timer that fires to redraw repeatedly over time whenever the color is changed. 一种解决方案是设置一个计时器,该计时器在每次更改颜色时都会随着时间的推移反复重绘。 When the user picks a new color, star an
NSTimer
that fires, say 10x a second. 当用户选择一种新颜色时,给
NSTimer
加上星号,然后每秒触发10次。 When the timer fires, update the current color to be partway from the start to the end color, and invalidate the view. 当计时器触发时,将当前颜色更新为从开始到结束的中间颜色,并使视图无效。 After you reach the final color, kill the timer.
达到最终颜色后,取消计时器。
I think it is better to use a CALayer to mask your view (don't forget to import QuartzCore): 我认为最好使用CALayer掩盖您的视图(不要忘记导入QuartzCore):
maskLayer.contents = (id)[UIImage imageNamed:maskName].CGImage; // maskLayer is a CALayer
view.layer.mask = maskLayer;
Now assuming you have a method -(void)animate
in your view controller, you have execute it multiple times using a timer, or using recursive calls to performSelector:withObject:afterDelay
. 现在假设您的视图控制器中有一个
-(void)animate
方法,您已经使用计时器多次执行了它,或者使用了递归调用来执行performSelector:withObject:afterDelay
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.