iOS 绘图(drawrect)图片裁剪的红色框框
随着手指在屏幕上滑会实时显示一个红色框框,可以用来裁剪图片。新建一个UIView类继承于UIView,在里面进行绘图操作。在需要的UIViewController里实现代理方法即可。图片裁剪方法,以后会详细介绍,这里不做讲解。效果图和代码如下:
// MyView.h
// 头像编辑
// Created by Dong on 15/5/8.
// Copyright (c) 2015年 Dong. All rights reserved.
#import <UIKit/UIKit.h>
// 代理传图片
@protocol getEditedImageDelegate <NSObject>
- (void)getNewImage:(CGRect)newRect;
@end
@interface MyView : UIView
@property (nonatomic, strong) UIImageView *imageView;
// 图片
@property (nonatomic, strong) UIImage *myImage;
@property (nonatomic, assign)id<getEditedImageDelegate>getImageDelegate;
@end
// MyView.m
// 头像编辑
// Created by Dong on 15/5/8.
// Copyright (c) 2015年 Dong. All rights reserved.
#import "MyView.h"
@implementation MyView
{
CGPoint firstTouch;
CGPoint lastTouch;
CGPoint lastTouch1;
}
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
}
return self;
}
// 开始触摸
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
// 获取触摸点
firstTouch = [touch locationInView:self];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
lastTouch = [touch locationInView:self];
/**
* 此时会实时绘制起始点与用户手指拖动点之间的形状
*/
[self setNeedsDisplay];
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
lastTouch = [touch locationInView:self];
[self setNeedsDisplay];
CGRect rec = CGRectMake(firstTouch.x, firstTouch.y, lastTouch.x - firstTouch.x, lastTouch.y - firstTouch.y);
/**
*
* 获取裁剪图片大小的代理方法
* */
[self.getImageDelegate getNewImage:rec];
}
// 获取矩形
- (CGRect)curRect
{
return CGRectMake(firstTouch.x, firstTouch.y, lastTouch.x - firstTouch.x, lastTouch.y - firstTouch.y);
}
- (void)drawRect:(CGRect)rect {
// Drawing code
// 获得设备上下文 把视图当做画布
CGContextRef context = UIGraphicsGetCurrentContext();
// 需要显示的红色框框
CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
CGContextStrokeRect(context, [self curRect]);
}
@end
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。