先上图:

OC(八)-APP-引导页广告加载 - 图1

实现思路:

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

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

  1. //
  2. // AppDelegate.m
  3. // ADLaunchImage
  4. //
  5. // Created by HMC on 16/10/17.
  6. // Copyright © 2016年 SKing. All rights reserved.
  7. //
  8. #import "AppDelegate.h"
  9. #import "ADView.h"
  10. @interface AppDelegate ()
  11. @end
  12. @implementation AppDelegate
  13. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  14. //网络测试
  15. NSString * imageURL = @"http://www.uisheji.com/forum.php?mod=attachment&aid=MTA5ODF8NGU1NzM3MDJ8MTQ3NjcyMTQ3MHwwfDU1NzA%3D&noupdate=yes&nothumb=yes";
  16. //本地测试
  17. NSString * imageURL1 = @"AD.png";
  18. //本地gif测试
  19. NSString * imageURL2 = @"ad.gif";
  20. ADView * adView = [[ADView alloc] initWithWindow:self.window sizeOfADImage:1.7 showTime:6 adImageURL:imageURL];
  21. adView.adImageClickedBlock = ^(NSInteger num){
  22. NSLog(@"在这里执行点击图片的操作,类型参数为:%ld",(long)num);
  23. };
  24. return YES;
  25. }

自定义 view代码.h

  1. //
  2. // ADView.h
  3. // ADLaunchImage
  4. //
  5. // Created by HMC on 16/10/17.
  6. // Copyright © 2016年 SKing. All rights reserved.
  7. //
  8. #import <UIKit/UIKit.h>
  9. #define screenWidth [[UIScreen mainScreen] bounds].size.width
  10. #define screenHeight [[UIScreen mainScreen] bounds].size.height
  11. @interface ADView : UIView
  12. //点击图片的 block
  13. @property (nonatomic, copy) void(^adImageClickedBlock)(NSInteger num);
  14. /**
  15. 初始化对象
  16. @param window window 窗口
  17. @param percentOfAdImage 广告图片大小(0 - 1)
  18. @param interval 广告图片展示时长
  19. @param imageURL 广告图片的 URL(网络) 或者 图片名字(本地)
  20. @return self
  21. */
  22. -(instancetype)initWithWindow:(UIWindow *)window sizeOfADImage:(CGFloat)percentOfAdImage showTime:(NSInteger)interval adImageURL:(NSString *)imageURL;
  23. @end

.m

  1. //
  2. // ADView.m
  3. // ADLaunchImage
  4. //
  5. // Created by HMC on 16/10/17.
  6. // Copyright © 2016年 SKing. All rights reserved.
  7. //
  8. #import "SADView.h"
  9. #import "UIImageView+WebCache.h"
  10. #import "UIImage+GIF.h"
  11. @interface SADView()
  12. @property (nonatomic, strong) NSTimer * timerOfShowAD;
  13. //广告图片
  14. @property (nonatomic, strong) UIImageView * adImage;
  15. //跳过按钮
  16. @property (nonatomic, strong) UIButton * skipButton;
  17. //广告图片的 URL
  18. @property (nonatomic, copy) NSString * imageURL;
  19. //本地广告图片名字
  20. @property (nonatomic, copy) NSString * localADImage;
  21. //广告图片的大小
  22. @property (nonatomic, assign)CGFloat percentOfAdImage;
  23. //显示时长
  24. @property (nonatomic, assign)NSInteger showTime;
  25. @end
  26. @implementation SADView
  27. -(instancetype)initWithWindow:(UIWindow *)window sizeOfADImage:(CGFloat)percentOfAdImage showTime:(NSInteger)interval adImageURL:(NSString *)imageURL{
  28. self.localADImage = @"AD.png";
  29. _percentOfAdImage = percentOfAdImage;
  30. self.showTime = interval;
  31. self.imageURL = imageURL;
  32. if (self = [super init]) {
  33. //活动窗口
  34. [window makeKeyAndVisible];
  35. CGSize screenSize = window.bounds.size;
  36. //设置启动图片
  37. NSString * launchImageName = nil;
  38. //设置竖屏
  39. NSString * screenDirection = @"Portrait";
  40. NSArray * launchImagesDict = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"UILaunchImages"];
  41. for (NSDictionary * dict in launchImagesDict) {
  42. NSString * imageDiretion = dict[@"UILaunchImageOrientation"];
  43. CGSize imageSize = CGSizeFromString(dict[@"UILaunchImageSize"]);
  44. if (CGSizeEqualToSize(screenSize, imageSize) && [screenDirection isEqualToString:imageDiretion]) {
  45. launchImageName = dict[@"UILaunchImageName"];
  46. }
  47. }
  48. //设置 self 的参数
  49. self.frame = window.bounds;
  50. self.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:launchImageName]];
  51. [self.adImage addSubview:self.skipButton];
  52. [self addSubview:self.adImage];
  53. [window addSubview:self];
  54. }
  55. return self;
  56. }
  57. #pragma mark - 按宽度 等比例缩放 注意:借用网上算法优化
  58. - (UIImage *)imageCompressForWidth:(UIImage *)sourceImage targetWidth:(CGFloat)defineWidth {
  59. UIImage *newImage = nil;
  60. CGSize imageSize = sourceImage.size;
  61. CGFloat width = imageSize.width;
  62. CGFloat height = imageSize.height;
  63. CGFloat targetWidth = defineWidth;
  64. CGFloat targetHeight = targetWidth * height / width ;
  65. CGSize size = CGSizeMake(targetWidth, targetHeight);
  66. CGFloat scaleFactor = 0.0;
  67. CGFloat scaledWidth = targetWidth;
  68. CGFloat scaledHeight = targetHeight;
  69. CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
  70. if(!CGSizeEqualToSize(imageSize, size)){
  71. CGFloat widthFactor = targetWidth / width;
  72. CGFloat heightFactor = targetHeight / height;
  73. scaleFactor = widthFactor > heightFactor? widthFactor :heightFactor;
  74. scaledWidth = width * scaleFactor;
  75. scaledHeight = height * scaleFactor;
  76. if(widthFactor > heightFactor){
  77. thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
  78. }else if(widthFactor < heightFactor){
  79. thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
  80. }
  81. }
  82. //重绘
  83. UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
  84. CGRect thumbnailRect = CGRectZero;
  85. thumbnailRect.origin = thumbnailPoint;
  86. thumbnailRect.size.width = scaledWidth;
  87. thumbnailRect.size.height = scaledHeight;
  88. [sourceImage drawInRect:thumbnailRect];
  89. newImage = UIGraphicsGetImageFromCurrentImageContext();
  90. UIGraphicsEndImageContext();
  91. return newImage;
  92. }
  93. -(UIImageView *)adImage{
  94. if (!_adImage) {
  95. _adImage = [UIImageView new];
  96. _adImage.contentMode = UIViewContentModeScaleAspectFit;
  97. _adImage.userInteractionEnabled = YES;
  98. if (_percentOfAdImage <= 1 && _percentOfAdImage > 0) {
  99. _adImage.frame = CGRectMake(0, 0, screenWidth, screenHeight * _percentOfAdImage);
  100. }else{
  101. _adImage.frame = CGRectMake(0, 0, screenWidth, screenHeight);
  102. }
  103. UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAD:)];
  104. [_adImage addGestureRecognizer:tap];
  105. CABasicAnimation * ani = [CABasicAnimation animationWithKeyPath:@"opacity"];
  106. ani.duration = 1.0;
  107. ani.fromValue = [NSNumber numberWithFloat:0.0];
  108. ani.toValue = [NSNumber numberWithFloat:1.0];
  109. ani.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
  110. [_adImage.layer addAnimation:ani forKey:@"animateOpacity"];
  111. }
  112. return _adImage;
  113. }
  114. -(UIButton *)skipButton
  115. {
  116. if (!_skipButton) {
  117. _skipButton = [UIButton buttonWithType:UIButtonTypeCustom];
  118. _skipButton.frame = CGRectMake(screenWidth- 85, 35, 65, 35);
  119. _skipButton.backgroundColor = [UIColor grayColor];
  120. _skipButton.titleLabel.textColor = [UIColor whiteColor];
  121. _skipButton.titleLabel.font = [UIFont systemFontOfSize:14.0];
  122. _skipButton.layer.masksToBounds = YES;
  123. _skipButton.layer.cornerRadius = 5.0;
  124. [_skipButton setTitle:[NSString stringWithFormat:@"跳过"] forState:UIControlStateNormal];
  125. [_skipButton addTarget:self action:@selector(skipAD:) forControlEvents:UIControlEventTouchUpInside];
  126. }
  127. return _skipButton;
  128. }
  129. -(void)setImageURL:(NSString *)imageURL{
  130. _imageURL = imageURL;
  131. if (imageURL) {
  132. [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:imageURL] options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
  133. if (image) {
  134. [self.adImage setImage:[self imageCompressForWidth:image targetWidth:screenWidth]];
  135. }else{
  136. if ([_imageURL rangeOfString:@".gif"].length) {
  137. NSData * gifImageData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:_imageURL ofType:nil]];
  138. self.adImage.image = [UIImage sd_animatedGIFWithData:gifImageData];
  139. }else{
  140. [self.adImage setImage: [self imageCompressForWidth:[UIImage imageNamed:_imageURL] targetWidth:screenWidth]];
  141. }
  142. }
  143. }];
  144. }
  145. //设置广告图片的定时器
  146. _timerOfShowAD = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(closeAD) userInfo:nil repeats:YES];
  147. }
  148. //跳过广告
  149. -(void)skipAD:(UIButton *)btn
  150. {
  151. NSLog(@"跳过广告");
  152. [self closeADView];
  153. }
  154. //点击广告
  155. -(void)tapAD:(UITapGestureRecognizer *)tapGestureRecognizer
  156. {
  157. NSLog(@"打开广告");
  158. if (self.adImageClickedBlock) {
  159. self.adImageClickedBlock(1);
  160. }
  161. }
  162. //关闭广告
  163. -(void)closeAD
  164. {
  165. if (self.showTime == 0) {
  166. NSLog(@"时间到,关闭广告");
  167. [self closeADView];
  168. }else{
  169. [self.skipButton setTitle:[NSString stringWithFormat:@"跳过(%@)", @(self.showTime--)] forState:UIControlStateNormal];
  170. }
  171. }
  172. //关闭动画
  173. -(void)closeADView{
  174. [UIView animateWithDuration:1.0 animations:^{
  175. self.alpha = 0.0;
  176. } completion:^(BOOL finished) {
  177. if (finished) {
  178. [_timerOfShowAD invalidate];
  179. _timerOfShowAD = nil;
  180. [self removeFromSuperview];
  181. }
  182. }];
  183. }
  184. @end

加载 gif 的效果

OC(八)-APP-引导页广告加载 - 图2

代码地址: 点这里