该程序中一个难点是使用CGImage来处理位图,虽然iOS提供了UIImage来代表位图,但实际上UIImage对位图的处理功能非常有限,如果需要对位图进行处理,则需要借助CGImage。
//
// ViewController.m
// 1113基于UIImageView的图片浏览器
//
// Created by weibiao on 15/11/13.
// Copyright © 2015年 weibiao. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
/**
* 存储图片的数组
*/
@property (nonatomic,strong) NSArray *images;
@property (nonatomic,assign) int curImage;
/**
* 透明度
*/
@property (nonatomic,assign) CGFloat alpha;
/**
* 增加透明度
*/
- (IBAction)plusAlpha:(id)sender;
/**
* 减小透明度
*/
- (IBAction)minusAlpha:(id)sender;
/**
* 下一张图片
*/
- (IBAction)nextImage:(id)sender;
@property (weak, nonatomic) IBOutletUIImageView *iv1;
@property (weak, nonatomic) IBOutletUIImageView *iv2;
@end
@implementation ViewController
- (void)viewDidLoad {
[superviewDidLoad];
self.alpha =1.0;
self.images = [NSArrayarrayWithObjects:@"Aerial01.jpg",@"Aerial02.jpg",@"Aerial03.jpg",@"Aerial04.jpg",@"Aerial05.jpg",nil];
// 启用iv1的用户交互,从而允许该控件能响应用户手势
self.iv1.userInteractionEnabled =YES;
// 创建一个手势检测器
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizeralloc] initWithTarget:selfaction:@selector(clicked:)];
// 为iv1添加手势检测器
[self.iv1addGestureRecognizer:singleTap];
}
- (IBAction)plusAlpha:(id)sender {
self.alpha +=0.02;
// 如果透明度已经大于或等于1.0,将透明度设置为1.0
if (self.alpha >=1.0) {
self.alpha =1.0;
}
self.iv1.alpha =self.alpha;
}
- (IBAction)minusAlpha:(id)sender {
self.alpha -=0.02;
// 如果透明度已经小于或等于0,将透明度设置为0;
if (self.alpha <=0) {
self.alpha =0;
}
self.iv1.alpha =self.alpha;
}
- (IBAction)nextImage:(id)sender {
self.iv1.image = [UIImageimageNamed:[self.imagesobjectAtIndex:++self.curImage %self.images.count]];
}
- (void)clicked:(UIGestureRecognizer *)gestureRecognizer {
// 获取正在显示的原始位图
UIImage *srcImage = self.iv1.image;
// 获取用户手指在iv控件上的触碰点
CGPoint pt = [gestureRecognizer locationInView:self.iv1];
// 获取正在显示的原图对应的CGImageRef
CGImageRef sourceImageRef = [srcImage CGImage];
// 获取图片的实际大小与第一个UIImageView的缩放比例
CGFloat scale = srcImage.size.width /320;
// 将iv控件上的触碰点的左边换算成原始图片的位置
CGFloat x = pt.x * scale;
CGFloat y = pt.y * scale;
if (x + 120 >srcImage.size.width) {
x = srcImage.size.width -203;
}
if (y + 120 > srcImage.size.height) {
y = srcImage.size.height -203;
}
// 调用CGImageCreateWithImageInRect函数获取sourceImageRef中指定区域的图片
CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, CGRectMake(x, y,203, 203));
// 让iv2控件显示newImageRef对应的图片
self.iv2.image = [UIImageimageWithCGImage:newImageRef];
}
@end