码迷,mamicode.com
首页 > 移动开发 > 详细

iOS 绘图(drawrect)图片裁剪的红色框框

时间:2015-05-21 15:40:39      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:图片裁剪   绘图   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




iOS 绘图(drawrect)图片裁剪的红色框框

标签:图片裁剪   绘图   drawrect   

原文地址:http://blog.csdn.net/xin__dong/article/details/45891011

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!