2011-03-29 87 views
1

我從currentview.but採取屏幕截圖圖像但我想設置框架... .don't要將fullview作爲image.I給框架大小..但它總是需要 圖像作爲fullview..any幫助嗎?如何將UIView轉換爲UIImage?

  CGRect rectt = CGRectMake(100, 150,150,200); 
    UIGraphicsBeginImageContext(rectt.size); 
    [self.layer renderInContext:UIGraphicsGetCurrentContext()]; 
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:rectt]; 

回答

3

嘗試使用這個子類:

// code to use the capture: 
    // in .h : #import "CaptureView.h" 
    CaptureView *cloneView = [[CaptureView alloc] initWithView:scrollView ]; 
    [scrollView addSubview:cloneView]; 

與此文件中的代碼

爲CaptureView.h:

#import <UIKit/UIKit.h> 
#import <QuartzCore/QuartzCore.h> 
#import <QuartzCore/CALayer.h> 


@interface CaptureView : UIView { 
@private 
    UIImage *_imageCapture; 
} 

@property(nonatomic, retain) UIImage *imageCapture; 

// Init 
- (id)initWithView:(UIView *)view; 

@end 

爲CaptureView.m:

#import "CaptureView.h" 

// Private 
@interface CaptureView (/* Private */) 
- (void)settingImageFromView:(UIView *)view; 
@end 

// Public 
@implementation CaptureView 

@synthesize imageCapture = _imageCapture; 

// Standard 
- (id)initWithFrame:(CGRect)frame { 

    if ((self = [super initWithFrame:frame])) { 
     // Initialization code. 
    } 
    return self; 
} 

// Init 
- (id)initWithView:(UIView *)view { 
// if ((self = [super initWithFrame:[view frame]])) { 
    if ((self = [super initWithFrame: CGRectMake(0, 0,150,200)])) { 
     // Initialization code. 
     [self settingImageFromView:view]; 
    } 
    return self; 
} 


- (void)settingImageFromView:(UIView *)view { 
// CGRect rect = [view bounds]; 
    CGRect rect = CGRectMake(100, 150,150,200); 
    UIGraphicsBeginImageContext(rect.size); 
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    [view.layer renderInContext:context]; 
    UIImage *imageCaptureRect; 

    imageCaptureRect = UIGraphicsGetImageFromCurrentImageContext(); 
    _imageCapture = imageCaptureRect; 
// _imageCapture = UIGraphicsGetImageFromCurrentImageContext(); 
// [_imageCapture retain]; 
    UIGraphicsEndImageContext(); 
} 


// Only override drawRect: if you perform custom drawing. 
// An empty implementation adversely affects performance during animation. 
- (void)drawRect:(CGRect)rect { 
    // Drawing code. 
    CGPoint accPoint = CGPointMake(0,0); 
    [_imageCapture drawAtPoint:accPoint]; 
} 


- (void)dealloc { 
    [_imageCapture release]; 
    [super dealloc]; 
} 

@end 
+2

此代碼的作品真的很好。一個小改進是自動讀取源UIView的寬度和高度: CGRect rect = CGRectMake(0,0,view.frame.size.width,view.frame.size.height); – 2012-04-30 15:38:46

+0

這崩潰像一個魅力 – 2016-11-18 07:57:05