Skip to content

Instantly share code, notes, and snippets.

@youngshook
Forked from mindbrix/NTBProxyImageView.h
Last active August 29, 2015 14:07
Show Gist options
  • Save youngshook/c057c48249a938c71175 to your computer and use it in GitHub Desktop.
Save youngshook/c057c48249a938c71175 to your computer and use it in GitHub Desktop.
//
// 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment