標籤:圖片裁剪 繪圖 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 = [superinitWithFrame:frame];
if (self) {
}
return self;
}
// 開始觸摸
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
// 擷取觸摸點
firstTouch = [touchlocationInView:self];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
lastTouch = [touchlocationInView:self];
/**
* 此時會即時繪製起始點與使用者手指拖動點之間的形狀
*/
[selfsetNeedsDisplay];
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
lastTouch = [touchlocationInView:self];
[selfsetNeedsDisplay];
CGRect rec = CGRectMake(firstTouch.x,firstTouch.y,lastTouch.x -firstTouch.x,lastTouch.y -firstTouch.y);
/**
*
* 擷取裁剪圖片大小的代理方法
* */
[self.getImageDelegategetNewImage:rec];
}
// 擷取矩形
- (CGRect)curRect
{
returnCGRectMake(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
iOS 繪圖(drawrect)圖片裁剪的紅色框框