iphone исчезновение изображений - PullRequest
8 голосов
/ 11 апреля 2011

Вт, я хочу, чтобы показать изображение в виде изображения и затемнить изображение через 5 секунд и показать следующее изображение. Изображения хранятся в массиве объектов ... я смог сделать успешный переход между изображениями после 5 секунд. То, что я хочу, это затемнить первое изображение через 5 секунд и показать следующее, которое должно произойти в бесконечном цикле ... ниже приведен код, и он действительно хорошо работает для нормального перехода между изображениями ... что я хочу, чтобы затухание изображений ... и нужно было добавить переход затухания в приведенный ниже код

- (void)viewDidLoad {

    imgView.animationImages=[NSArray arrayWithObjects:  
                             [UIImage imageNamed:@"lori.png"],
                             [UIImage imageNamed:@"miranda.png"],
                             [UIImage imageNamed:@"taylor.png"],
                             [UIImage imageNamed:@"ingrid.png"],
                             [UIImage imageNamed:@"kasey.png"], 
                             [UIImage imageNamed:@"wreckers.png"], nil];


    imgView.animationDuration=20.0;
    imgView.animationRepeatCount=0;
    [imgView startAnimating];
    [self.view addSubview:imgView];
    [imgView release];



    [super viewDidLoad];
}

Ответы [ 3 ]

5 голосов
/ 11 апреля 2011

Вы можете использовать повторяющийся NSTimer для вызова специального метода, который непрерывно анимирует альфа-свойство представлений изображений от 0,0 до 1,0. Вот код, который я написал, который работает:

- (void)viewDidLoad {
    imgView.animationImages=[NSArray arrayWithObjects:  
                             [UIImage imageNamed:@"lori.png"],
                             [UIImage imageNamed:@"miranda.png"],
                             [UIImage imageNamed:@"taylor.png"],
                             [UIImage imageNamed:@"ingrid.png"],
                             [UIImage imageNamed:@"kasey.png"], 
                             [UIImage imageNamed:@"wreckers.png"], nil];



    imgView.animationDuration=20.0;
    imgView.animationRepeatCount=0;
    [imgView startAnimating];
    [self.view addSubview:imgView];
    [imgView release];
    //The timers time interval is the imageViews animation duration devided by the number of images in the animationImages array. 20/5 = 4 
    NSTimer *timer = [NSTimer timerWithTimeInterval:4.0 
                                              target:self 
                                            selector:@selector(onTimer) 
                                            userInfo:nil 
                                             repeats:YES];

    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    [timer fire];

    [super viewDidLoad];
}

//It is important that the animation durations within these animation blocks add up to 4 
//(the time interval of the timer). If you change the time interval then the time intervals 
//in these blocks must also be changed to refelect the amount of time an image is displayed. 
//Failing to do this will mean your fading animation will go out of phase with the switching of images.   

-(void)onTimer{
        [UIView animateWithDuration:3.0 animations:^{
            imgView.alpha = 0.0; 
        }];
        [UIView animateWithDuration:1.0 animations:^{
            imgView.alpha = 1.0; 
        }];
    }

Если вы хотите, чтобы длительность замирания длилась 5 секунд вместо 4, вам нужно увеличить свойство animationDuration просмотра изображений до 25, а затем увеличить длительность анимации замирания в двух блоках, чтобы суммарное время затухания = 5.

3 голосов
/ 27 января 2012

Вот что сработало для меня, когда я хотел анимировать набор сообщений в виде изображений для пользователя.Независимо от того, сколько изображений у вас есть этот код будет проходить через них.

[self.messageBottom = [[UIImageView alloc] initWithFrame:CGRectMake(289, 262, 171, 38)];
[self addSubview:messageBottom];
[messageBottom setAlpha:0.0];
[messageBottom release];

self.messageTop = [[UIImageView alloc] initWithFrame:CGRectMake(289, 262, 171, 38)];
[self addSubview:messageTop];
[messageTop setAlpha:1.0];
[messageTop release];


self.messageImgsArray =[NSArray arrayWithObjects:  
                        [UIImage imageNamed:@"image1.png"],
                        [UIImage imageNamed:@"image2.png"],
                        [UIImage imageNamed:@"image3.png"],
                        [UIImage imageNamed:@"image4.png"],
                        [UIImage imageNamed:@"image5.png"],nil];


topIndex = 0, bottomIndex = 1;     
[messageTop setImage:[messageImgsArray objectAtIndex:topIndex]];

//The timers time interval is the imageViews animation duration devided by the number of images in the animationImages array. 20/5 = 4 
NSTimer *timer = [NSTimer timerWithTimeInterval:2.0 
                                         target:self 
                                       selector:@selector(onTimer) 
                                       userInfo:nil 
                                        repeats:YES];

[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

}


-(void)onTimer{

    [UIView animateWithDuration:1 animations:^{

        //set the image of the image that is not currently visible

        if (messageTop.alpha == 0) {
            [messageTop setImage:[messageImgsArray objectAtIndex:topIndex]];
        }
        if (messageBottom.alpha == 0) {
            [messageBottom setImage:[messageImgsArray objectAtIndex:bottomIndex]];
        }

        //make sure the images rotate
        [messageTop setAlpha:messageTop.alpha == 0 ? 1 : 0];
        [messageBottom setAlpha:messageBottom.alpha == 0 ? 1 : 0];

        //make sure the images play in a loop

        topIndex = topIndex < [messageImgsArray count]-1 ? bottomIndex+1 : 0;
        bottomIndex = bottomIndex < [messageImgsArray count]-1 ? bottomIndex+1 : 0;

    }];
}
3 голосов
/ 11 апреля 2011

@ user652878 Это отвечает на ваш вопрос о безрадостном выцветании от одного изображения к следующему:

Создайте следующие свойства в заголовке контроллеров представления:

UIImageView *imageViewBottom, *imageViewTop;
    NSArray *imageArray; 

Затем добавьте этот код в свойфайл имплиментации:

int topIndex = 0, prevTopIndex = 1; 
- (void)viewDidLoad {

    imageViewBottom = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,320,480)];
    [self.view addSubview:imageViewBottom]; 

    imageViewTop = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,320,480)];
    [self.view addSubview:imageViewTop];

    imageArray = [NSArray arrayWithObjects:  
                  [UIImage imageNamed:@"lori.png"],
                  [UIImage imageNamed:@"miranda.png"],
                  [UIImage imageNamed:@"taylor.png"],
                  [UIImage imageNamed:@"ingrid.png"],
                  [UIImage imageNamed:@"kasey.png"], 
                  [UIImage imageNamed:@"wreckers.png"], nil];


    NSTimer *timer = [NSTimer timerWithTimeInterval:5.0 
                                              target:self 
                                            selector:@selector(onTimer) 
                                            userInfo:nil 
                                             repeats:YES];

    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    [timer fire];

    [super viewDidLoad];
}

-(void)onTimer{
    if(topIndex %2 == 0){
        [UIView animateWithDuration:5.0 animations:^
        {
            imageViewTop.alpha = 0.0;
        }]; 
        imageViewTop.image = [imageArray objectAtIndex:prevTopIndex];
        imageViewBottom.image = [imageArray objectAtIndex:topIndex];
    }else{
        [UIView animateWithDuration:5.0 animations:^
         {
             imageViewTop.alpha = 1.0;
         }];    
        imageViewTop.image = [imageArray objectAtIndex:topIndex];
        imageViewBottom.image = [imageArray objectAtIndex:prevTopIndex];
    }
    prevTopIndex = topIndex; 
    if(topIndex == [imageArray count]-1){
        topIndex = 0; 
    }else{
        topIndex++; 
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...