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

代码地址: 点这里

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,843评论 6 502
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,538评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,187评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,264评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,289评论 6 390
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,231评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,116评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,945评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,367评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,581评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,754评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,458评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,068评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,692评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,842评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,797评论 2 369
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,654评论 2 354

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,085评论 25 707
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,096评论 4 62
  • Part 1 They found a coffin. There is a remote village.In ...
    铁打的星星66阅读 653评论 8 2
  • 2015.10.9晚上18:00妈妈我来了,我习惯在妈妈肚子里,的世界所以我紧闭双眼,但是我有个顺风耳。听到亲...
    天使龙宝阅读 449评论 0 1
  • 晚上10:45,在还亮灯迎客的兰州拉面和沙县小吃店门前沉思了2秒后,进了沙县。 来笼蒸饺,蘸小碟芝麻酱的那种,摘下...
    MeLola阅读 266评论 0 0