OC(八):APP 引导页广告加载

先上图:

2016-10-17 23_26_55.gif

实现思路:

实例化view 添加到 window上,在 view上添加广告图片,跳过按钮,再做它们的相应的点击事件处理,需要引入第三方库 SDWebImage, 切记.
妥啦,就是这么简单.来上代码.

调用代码 (三行搞定) AppDelegate.m

//
//  AppDelegate.m
//  ADLaunchImage
//
//  Created by HMC on 16/10/17.
//  Copyright © 2016年 SKing. All rights reserved.
//

#import "AppDelegate.h"
#import "ADView.h"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    //网络测试
    NSString * imageURL = @"http://www.uisheji.com/forum.php?mod=attachment&aid=MTA5ODF8NGU1NzM3MDJ8MTQ3NjcyMTQ3MHwwfDU1NzA%3D&noupdate=yes&nothumb=yes";
    //本地测试
    NSString * imageURL1 = @"AD.png";
    //本地gif测试
    NSString * imageURL2 = @"ad.gif";
    ADView * adView = [[ADView alloc] initWithWindow:self.window sizeOfADImage:1.7 showTime:6 adImageURL:imageURL];
    adView.adImageClickedBlock = ^(NSInteger num){
    
        NSLog(@"在这里执行点击图片的操作,类型参数为:%ld",(long)num);
        
    };
    
    return YES;
}

自定义 view代码.h

//
//  ADView.h
//  ADLaunchImage
//
//  Created by HMC on 16/10/17.
//  Copyright © 2016年 SKing. All rights reserved.
//

#import <UIKit/UIKit.h>

#define screenWidth      [[UIScreen mainScreen] bounds].size.width
#define screenHeight     [[UIScreen mainScreen] bounds].size.height


@interface ADView : UIView

//点击图片的 block
@property (nonatomic, copy) void(^adImageClickedBlock)(NSInteger num);



/**
 初始化对象

 @param window           window 窗口
 @param percentOfAdImage 广告图片大小(0 - 1)
 @param interval         广告图片展示时长
 @param imageURL         广告图片的 URL(网络) 或者 图片名字(本地)

 @return self
 */
-(instancetype)initWithWindow:(UIWindow *)window sizeOfADImage:(CGFloat)percentOfAdImage showTime:(NSInteger)interval adImageURL:(NSString *)imageURL;

@end

.m

//
//  ADView.m
//  ADLaunchImage
//
//  Created by HMC on 16/10/17.
//  Copyright © 2016年 SKing. All rights reserved.
//

#import "SADView.h"
#import "UIImageView+WebCache.h"
#import "UIImage+GIF.h"

@interface SADView()

@property (nonatomic, strong) NSTimer * timerOfShowAD;
//广告图片
@property (nonatomic, strong) UIImageView * adImage;
//跳过按钮
@property (nonatomic, strong) UIButton * skipButton;
//广告图片的 URL
@property (nonatomic, copy) NSString * imageURL;
//本地广告图片名字
@property (nonatomic, copy) NSString * localADImage;
//广告图片的大小
@property (nonatomic, assign)CGFloat percentOfAdImage;
//显示时长
@property (nonatomic, assign)NSInteger showTime;

@end

@implementation SADView


-(instancetype)initWithWindow:(UIWindow *)window sizeOfADImage:(CGFloat)percentOfAdImage showTime:(NSInteger)interval adImageURL:(NSString *)imageURL{
    
    self.localADImage = @"AD.png";
    _percentOfAdImage = percentOfAdImage;
    self.showTime = interval;
    self.imageURL = imageURL;
    
    if (self = [super init]) {
        
        //活动窗口
        [window makeKeyAndVisible];
        CGSize screenSize = window.bounds.size;
        
        //设置启动图片
        NSString * launchImageName = nil;
        //设置竖屏
        NSString * screenDirection = @"Portrait";
        NSArray * launchImagesDict = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"UILaunchImages"];
        
        for (NSDictionary * dict in launchImagesDict) {
            NSString * imageDiretion = dict[@"UILaunchImageOrientation"];
            CGSize imageSize = CGSizeFromString(dict[@"UILaunchImageSize"]);
            if (CGSizeEqualToSize(screenSize, imageSize) && [screenDirection isEqualToString:imageDiretion])  {
                
                launchImageName = dict[@"UILaunchImageName"];
            }
            
        }
        
        
        //设置 self 的参数
        self.frame = window.bounds;
        self.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:launchImageName]];
        
        
        [self.adImage addSubview:self.skipButton];
        [self addSubview:self.adImage];
        [window addSubview:self];
        
        
    }
    
    return self;
}


#pragma mark - 按宽度 等比例缩放  注意:借用网上算法优化
- (UIImage *)imageCompressForWidth:(UIImage *)sourceImage targetWidth:(CGFloat)defineWidth {
    
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    
    CGFloat targetWidth = defineWidth;
    CGFloat targetHeight = targetWidth * height / width ;
    CGSize size = CGSizeMake(targetWidth, targetHeight);
    
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
    
    if(!CGSizeEqualToSize(imageSize, size)){
        
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        scaleFactor = widthFactor > heightFactor?  widthFactor :heightFactor;
        
        scaledWidth = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        if(widthFactor > heightFactor){
            
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
            
        }else if(widthFactor < heightFactor){
            
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    //重绘
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return newImage;
}


-(UIImageView *)adImage{
    
    if (!_adImage) {
        
        _adImage = [UIImageView new];
        _adImage.contentMode = UIViewContentModeScaleAspectFit;
        _adImage.userInteractionEnabled = YES;
        
        if (_percentOfAdImage <= 1 && _percentOfAdImage > 0) {
            
            _adImage.frame = CGRectMake(0, 0, screenWidth, screenHeight * _percentOfAdImage);
        }else{
            
            _adImage.frame = CGRectMake(0, 0, screenWidth, screenHeight);
        }
        
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAD:)];
        [_adImage addGestureRecognizer:tap];
        
        CABasicAnimation * ani = [CABasicAnimation animationWithKeyPath:@"opacity"];
        ani.duration = 1.0;
        ani.fromValue = [NSNumber numberWithFloat:0.0];
        ani.toValue = [NSNumber numberWithFloat:1.0];
        ani.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
        [_adImage.layer addAnimation:ani forKey:@"animateOpacity"];
        
        
    }
    return _adImage;
}

-(UIButton *)skipButton
{
    if (!_skipButton) {
        
        _skipButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _skipButton.frame = CGRectMake(screenWidth- 85, 35, 65, 35);
        _skipButton.backgroundColor = [UIColor grayColor];
        _skipButton.titleLabel.textColor = [UIColor whiteColor];
        _skipButton.titleLabel.font = [UIFont systemFontOfSize:14.0];
        _skipButton.layer.masksToBounds = YES;
        _skipButton.layer.cornerRadius = 5.0;
        [_skipButton setTitle:[NSString stringWithFormat:@"跳过"] forState:UIControlStateNormal];
        [_skipButton addTarget:self action:@selector(skipAD:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _skipButton;
}

-(void)setImageURL:(NSString *)imageURL{
    
    _imageURL = imageURL;
    
    if (imageURL) {
        
        [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:imageURL] options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
            
            if (image) {
                
                [self.adImage setImage:[self imageCompressForWidth:image targetWidth:screenWidth]];
                
            }else{
                
                if ([_imageURL rangeOfString:@".gif"].length) {
                    
                    NSData * gifImageData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:_imageURL ofType:nil]];
                    self.adImage.image = [UIImage sd_animatedGIFWithData:gifImageData];
                    
                }else{
                    
                    [self.adImage setImage: [self imageCompressForWidth:[UIImage imageNamed:_imageURL] targetWidth:screenWidth]];
                    
                }
            }
        }];
    }
    
    //设置广告图片的定时器
    _timerOfShowAD = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(closeAD) userInfo:nil repeats:YES];
    
    
    
}


//跳过广告
-(void)skipAD:(UIButton *)btn
{
    NSLog(@"跳过广告");
    [self closeADView];
    
}

//点击广告

-(void)tapAD:(UITapGestureRecognizer *)tapGestureRecognizer
{
    
    NSLog(@"打开广告");
    if (self.adImageClickedBlock) {
        
        self.adImageClickedBlock(1);
    }
}

//关闭广告

-(void)closeAD
{
    if (self.showTime == 0) {
        NSLog(@"时间到,关闭广告");
        
        [self closeADView];
        
    }else{
        
        [self.skipButton setTitle:[NSString stringWithFormat:@"跳过(%@)", @(self.showTime--)] forState:UIControlStateNormal];
    }
}

//关闭动画
-(void)closeADView{
    
    [UIView animateWithDuration:1.0 animations:^{
        self.alpha = 0.0;
    } completion:^(BOOL finished) {
        if (finished) {
            
            [_timerOfShowAD invalidate];
            _timerOfShowAD = nil;
            [self removeFromSuperview];
        }
    }];
}

@end

加载 gif 的效果

2016-10-18 02_18_02.gif

代码地址: 点这里

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值