youngshook
10/11/2014 - 12:17 PM

NTBProxyImageView.h

//
//  NTBProxyImageView.h
//  Vectoria Squared
//
//  Created by Nigel Barber on 22/04/2013.
//  Copyright (c) 2013 Nigel Barber. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface NTBProxyImageView : UIImageView


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

-(void)drawAfterUpdate:(void (^)(void))updateBlock;


@end
//
//  NTBProxyImageView.m
//  Vectoria Squared
//
//  Created by Nigel Barber on 22/04/2013.
//  Copyright (c) 2013 Nigel Barber. All rights reserved.
//

#import <QuartzCore/QuartzCore.h>

#import "NTBProxyImageView.h"



@interface NTBProxyImageView ()

@property( nonatomic, assign ) dispatch_semaphore_t  renderingSemaphore;
@property( nonatomic, assign ) dispatch_queue_t renderingQueue;

@property( nonatomic, retain ) UIView *view;

@end




@implementation NTBProxyImageView


-(id)initWithView:(UIView *)view
{
    self = [ super initWithFrame:view.frame ];
    
    if( self )
    {
        self.view = view;
        
        if( view.superview )
        {
            [ view removeFromSuperview ];
        }
        
        _renderingSemaphore = dispatch_semaphore_create( 1 );
        _renderingQueue = dispatch_queue_create( "uk.co.mindbrix.NTBProxyImageView", DISPATCH_QUEUE_SERIAL );
    }
    
    return self;
}


-(void)dealloc
{
    [ super dealloc ];
    
    dispatch_release( _renderingQueue );
    
    [ _view release ];
}



-(void)drawAfterUpdate:(void (^)(void))updateBlock
{
    if( self.view && updateBlock )
    {
        if (dispatch_semaphore_wait( _renderingSemaphore, DISPATCH_TIME_NOW ) != 0 )
        {
            return;
        }
        
        dispatch_async( _renderingQueue, ^()
                       {
                           updateBlock();
                           
                           UIImage *image = [ self imageFromView:self.view ];
                           
                           dispatch_async( dispatch_get_main_queue(), ^()
                                         {
                                             self.image = image;
                                         });
                           
                        
                           dispatch_semaphore_signal( _renderingSemaphore );
                           
                       });
    }
}



-(UIImage *)imageFromView:(UIView *)view
{
	if( [ view.layer respondsToSelector:@selector(setShouldRasterize:)])
	{
		UIGraphicsBeginImageContextWithOptions( view.bounds.size, NO, view.contentScaleFactor );
	}
	else
	{
		UIGraphicsBeginImageContext( view.bounds.size );
	}
	
	[ view.layer renderInContext:UIGraphicsGetCurrentContext() ];
	UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	
	return image;
}



@end