Posts Tagged ‘UIImage’

[iOS] UIImage CGImage clipping and copy in rect

Wednesday, December 22nd, 2010

I created useful UIimage utilty class.


#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface UIImageDrawUtil : NSObject {

 * clipping sourceImage in sourceRect. and copy it to targetImage in destPoint
 * returns new UIImage
 * This dimension is in UIImage, not in QuarzCore
+ (UIImage *)copyPixels:(UIImage *)targetImage sourceImage:(UIImage *)sourceImage sourceRect:(CGRect)sourceRect destPoint:(CGPoint)destPoint;


#import "UIImageDrawUtil.h"
#import <QuartzCore/QuartzCore.h>

@implementation UIImageDrawUtil
+ (UIImage *)copyPixels:(UIImage *)targetImage sourceImage:(UIImage *)sourceImage sourceRect:(CGRect)sourceRect destPoint:(CGPoint)destPoint
	CGImageRef tempImage = CGImageCreateWithImageInRect(sourceImage.CGImage, sourceRect);
	int tw = targetImage.size.width;
	int th = targetImage.size.height;
	int tempw = CGImageGetWidth(tempImage);
	int temph = CGImageGetHeight(tempImage);

	UIGraphicsBeginImageContext(CGSizeMake(tw, th));
	CGContextRef ctx = UIGraphicsGetCurrentContext();
	CGContextTranslateCTM(ctx, 0, th);
	CGContextScaleCTM(ctx, 1.0, -1.0);
	CGContextDrawImage(ctx, CGRectMake(0, 0, tw, th), targetImage.CGImage);	
	CGContextClipToRect(ctx, CGRectMake(destPoint.x, th - temph -destPoint.y, tempw, temph));
	CGContextDrawImage(ctx, CGRectMake(destPoint.x, th - temph -destPoint.y, tempw, temph), tempImage);
	UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
	tempImage = NULL;
	return newImage;

how to use

There is 400 x 400 png.
This name is myimage.png.

and write below code.

- (void)viewDidLoad {
    [super viewDidLoad];
	NSString *path = [[NSBundle mainBundle] pathForResource:@"myimage" ofType:@"png"];
	UIImage *img = [[UIImage alloc] initWithContentsOfFile:path];
	CGImageRef clipImage = CGImageCreateWithImageInRect(img.CGImage, CGRectMake(0, 100, 100, 200));
	UIImage *newImage = [UIImageDrawUtil copyPixels:[UIImage imageWithCGImage:clipImage] sourceImage:img sourceRect:CGRectMake(100, 0, 100, 100) destPoint:CGPointMake(0, 50)];
	UIImageView *imgView = [[UIImageView alloc] initWithImage:newImage];
	[self.view addSubview:imgView];
	clipImage = nil;
	newImage = nil;

	[imgView release];
	imgView = nil;
	[img release];
	img = nil;

Then result is

[iOS] NSData to NSString or UIImage

Thursday, June 24th, 2010

NSData to NSString

NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

NSData to UIImage

UIimage *img = [[UIImage alloc] initWithData:data];

refer to
>> エンコードを指定して、NSData <-> NSString を変換する
>> UIImageとNSDataの相互変換