-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch * touch = [touches anyObject];
p1 = [touch locationInView:self];
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch * touch = [touches anyObject];
p2 = [touch locationInView:self];
[selfsetNeedsDisplay];
}
-(void)drawRect:(CGRect)rect
{
CGContextRef ct =UIGraphicsGetCurrentContext();
CGColorRef color = [UIColorlightGrayColor].CGColor;
CGContextSetStrokeColorWithColor(ct, color);
CGContextSetLineWidth(ct,2.0);
/*
CGContextMoveToPoint(ct, p1.x, p1.y);
CGContextAddLineToPoint(ct, p1.x, p2.y);
CGContextAddLineToPoint(ct, p2.x, p2.y);
CGContextAddLineToPoint(ct, p2.x, p1.y);
CGContextAddLineToPoint(ct, p1.x, p1.y);
*/
CGContextStrokeRect(ct, CGRectMake(p1.x, p1.y, p2.x -p1.x, p2.y -p1.y));
CGContextStrokePath(ct);
[selfsetNeedsDisplay];
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UIView * Aview = [[UIViewalloc]initWithFrame:self.window.frame];
Aview.backgroundColor = [UIColorwhiteColor];
[self.window addSubview:Aview];
// 在图片显示的时候,有时需要只显示某一个区域,这时就需要用到类CGImageRef去剪切出来图片中的一块来!
//
// 假设要从A图片上显示出B这一部分,那么
//
// 首先要获得要剪切一片区域的原图片A(UIImage),然后还要获要要剪切的区域大小B(CGRect)。
//
// 就可以开始剪切了(CGImageView),最后把剪切出来的B显示到视图上(UIImageview);
//
UIImage * ima = [UIImageimageNamed:@"3.png"];//原图片
//获得剪切的区域B
CGImageRef image =CGImageCreateWithImageInRect([ima CGImage],CGRectMake(p1.x,p1.y,p2.x -p1.x,p2.y -p1.y));
UIImage * subIma = [UIImageimageWithCGImage:image];//把b转化成为一张图片
UIImageView * imageView = [[UIImageViewalloc]initWithFrame:CGRectMake(p1.x,p1.y, p2.x -p1.x, p2.y -p1.y)];
imageView.image = subIma;//在视图上加载图片B
[self.window addSubview:imageView];//把图片显示在视图上
}
@end