UIView animated backgroundColor with drawRect:

喜夏-厌秋 提交于 2019-12-10 19:06:58

问题


I have a view that is able to draw a rect on itself. It is actually a subclass of UICollectionView but I'm just struggling with UIView specific stuff; the backgroundColor.

I simply added a UIPanGestureRecognizer, saved the start point at UIGestureRecognizerStateBegan and the end point at UIGestureRecognizerStateChanged. I then use the -drawRect: method to draw the actual path:

- (void)awakeFromNib {
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGesture:)];
    [self addGestureRecognizer:pan];
}

- (void)panGesture:(UIPanGestureRecognizer *)panRecon {
    if([panRecon state] == UIGestureRecognizerBegan) {
        startPoint = [panRecon locationInView:self];
    }
    else if([panRecon state] == UIGestureRecognizerChanged) {
        endPoint = [panRecon locationInView:self];
        [self setNeedsDisplay];
    }
    else if([panRecon state] == UIGestureRecognizerEnded /* || failed || cancelled */) {
        startPoint = CGPointZero;
        endPoint = CGPointZero;
        [self setNeedsDisplay];
    }
}

- (void)drawRect:(CGRect)rect {
    if(!CGPointEqualToPoint(startPoint, CGPointZero) && !CGPointEqualToPoint(endPoint, CGPointZero)) {
        CGRect selectionRect = CGRectMake(startPoint.x, startPoint.y, endPoint.x - startPoint.x, endPoint.y - startPoint.y);


        [[UIColor colorWithWhite:1.0 alpha:0.3] setFill];
        [[UIColor colorWithWhite:1.0 alpha:1.0] setStroke];

        CGContextFillRect(UIGraphicsGetCurrentContext(), selectionRect);
        CGContextStrokeRect(UIGraphicsGetCurrentContext(), selectionRect);
    }
}

I now want to start the selection mode (which the rect should actually be) with the view flashing. I created a UIView animation for that:

- (void)startSelection {
    [UIView animateWithDuration:0.2 delay:0.0 options:UIViewAnimationOptionCurveEaseIn animations:^{
        [self setBackgroundColor:[UIColor whiteColor]];
    } completion:^(BOOL finished){
        if(finished) {
            [UIView animateWithDuration:0.9 delay:0.0 options:UIViewAnimationOptionCurveEaseOut animations:^{
                [self setBackgroundColor:[UIColor blackColor]];
            } completion:nil];
        }
    }
}

The problem is: once I implement the -drawRect: method, UIView does not animate the backgroundColor change anymore. I already tried UIViewAnimationOptionAllowAnimatedContent and almost everything I could find on google, but I wasn't able to solve my problem.

Does anybody know how I can animate backgroundColor of an UIView and have -drawRect: implemented?

来源:https://stackoverflow.com/questions/20197431/uiview-animated-backgroundcolor-with-drawrect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!