Animating UIImageView with colorWithPatternImage

时光毁灭记忆、已成空白 提交于 2019-12-10 10:59:54

问题


I have a UIImageView that is animated using the following code:

    NSMutableArray *imageArray = [[NSMutableArray alloc] init];

    for(int i = 1; i < 15; i++) {
        NSString *str = [NSString stringWithFormat:@"marker_%i.png", i];
        UIImage *img = [UIImage imageNamed:str];
        if(img != nil) {
            [imageArray addObject:img];
        }

    }

    _imageContainer.animationImages = imageArray;

    _imageContainer.animationDuration = 0.5f;
    [_imageContainer startAnimating];

What I want now is to repeat the image to get a pattern. There is colorWithPatternImage, but that isn't made for animations.

I want the whole background filled with a animated pattern. Instead of using a very large images (960x640) i could use a image of 64x64 for example and repeat that to fill the screen.

Is there any way?


回答1:


Leave your code as it is, but instead using UIImageView use my subclass:

//
//  AnimatedPatternView.h
//

#import <UIKit/UIKit.h>

@interface AnimatedPatternView : UIImageView;    
@end

//
//  AnimatedPatternView.m
//

#import "AnimatedPatternView.h"

@implementation AnimatedPatternView

-(void)setAnimationImages:(NSArray *)imageArray
{
    NSMutableArray* array = [NSMutableArray arrayWithCapacity:imageArray.count];

    for (UIImage* image in imageArray) {
        UIGraphicsBeginImageContextWithOptions(self.bounds.size, YES, 0);
        UIColor* patternColor = [UIColor colorWithPatternImage:image];
        [patternColor setFill];
        CGContextRef ctx = UIGraphicsGetCurrentContext();
        CGContextFillRect(ctx, self.bounds);
        UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        [array addObject:img];

    }
    [super setAnimationImages:array];
}

@end

If you create the view using interface builder you only need to set the class of the image view in the identity inspector.



来源:https://stackoverflow.com/questions/16461469/animating-uiimageview-with-colorwithpatternimage

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