iOS 繪圖(drawrect)圖片裁剪的紅色框框

來源:互聯網
上載者:User

標籤:圖片裁剪   繪圖   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)圖片裁剪的紅色框框

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.