This line of code has no effect. It does not change orientation of the image. What am I doing wrong?
// image is of type UIImage
UIImage * newImage = [UIImage imageWithCGImage:[image CGImage] scale:image.scale orientation:UIImageOrientationLeft];
Refer to the definition of this method below, make sure your CGImage is of a CGImageRef class.
imageWithCGImage:[image CGImage]
+(UIImage *)imageWithCGImage:(CGImageRef)imageRef scale:(CGFloat)scale orientation:(UIImageOrientation)orientation
Following three lines are some initializations before you call the method.
CIContext * context = [CIContext contextWithOptions:nil]; //your choice
CIImage * OriginalImage = [CIImage imageWithContentsOfURL:fileNameAndPath]; //your own choice of source image file.
CGImageRef CGImage = [context createCGImage:OriginalImage fromRect:(CGRect)];
UIImage *newImage = [UIImage imageWithCGImage:CGImage scale:1.0 orientation:UIImageOrientationLeft]
Hope this helps.
Related
I have developed a project, where a user draws a image on a canvas, I store it in the file using CoreData, I have one-to-many relationship called folder-to-files. So here all are images. I retrive the images from files , resize according to my table cell height and show it on a table. Once it is shown, I want to cache the images.
I also have some labels on the folder cell, which give me some info regarding my files, which I update on fly.
I also swipe the cells to mark it complete and move it to the bottom the cell.
I also show same file images in different Views depending on how user queries it.
I want to know the best method for this, I read through the web, their are many methods, GCD, NSOperationQueues and many more.
Which method will be best suited for me.
I want to show some code
- (UITableViewCell *)tableView:(FMMoveTableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
FolderCell *tableCell = (FolderCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (tableCell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"FolderCell" owner:self options:nil];
tableCell = [nib objectAtIndex:0];
}
NSMutableArray *categoryArray = [[self.controller fetchedObjects]mutableCopy];
Folder *category = [categoryArray objectAtIndex:[indexPath row]];
[tableCell configureCellWithNote:category]; //This function is written in my FolderCell.m function
}
return tableCell;
}
-(void)configureCellWithNote:(Folder *)category
{
self.category = category;
UIImage *image1 = [UIImage imageWithData:category.noteImage];
CGSize newSize;
if(image1.size.width == 620 && image1.size.height == 200)
{
newSize = CGSizeMake(300, 97);
}
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[image1 drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.notesImage.image = newImage;
}
So what is happening here is that configureCellWithNote is taking lot of time, because it is resizing images. Please help me out in deciding how can this performance issue be solved.
Regards
Rajit
If you simply want to shuffle the resize operation to a background thread, you could do something like this:
- (void)configureCellWithNote:(Folder *)category
{
self.category = category;
UIImage *image1 = [UIImage imageWithData:category.noteImage];
CGSize newSize;
if(image1.size.width == 620 && image1.size.height == 200)
{
newSize = CGSizeMake(300, 97);
}
dispatch_async(dispatch_get_global_queue(0,0), ^{
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[image1 drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
dispatch_async(dispatch_get_main_queue(), ^{
self.notesImage.image = newImage;
});
});
}
If you want to cache the results, then the trick will be to come up with a good cache key. Unfortunately, it's hard to tell from what you've posted what would make a good cache key. Certainly it will need to include the size, but it'll also need to include something that ties it back to the category. I suppose if nothing else you could use the NSManagedObjectID for the category, but I think that'll be specific to each managed object context you have. Assuming there was a property on Folder called uniqueName a caching implementation might look like this:
- (UIImage*)imageForCategory: (Folder*)category atSize: (CGSize)size
{
// A shared (i.e. global, but scoped to this function) cache
static NSCache* imageCache = nil;
// The following initializes the cache once, and only once
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
imageCache = [[NSCache alloc] init];
});
// Generate a cache key sufficient to uniquely identify the image we're looking for
NSString* cacheKey = [NSString stringWithFormat: #"%#|%#", category.uniqueName, NSStringFromSize((NSSize)size)];
// Try fetching any existing image for that key from the cache.
UIImage* img = [imageCache objectForKey: cacheKey];
// If we don't find a pre-existing one, create one
if (!img)
{
// Your original code for creating a resized image...
UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
UIImage* image1 = [UIImage imageWithData:category.noteImage];
[image1 drawInRect:CGRectMake(0,0,size.width,size.height)];
img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// Now add the newly-created image to the cache
[imageCache setObject: img forKey: cacheKey];
}
// Return the image
return img;
}
I'm creating many colour variations of an image using Core Graphics. I need to create about 320 in total but gradually, the memory usage of the app keeps increasing until it crashes. From Instruments, I see that more CGImage objects are being created and stay alive. I want to release them because I store the images to the cache directory in PNG format.
I have searched through all other solutions I could find without success. Any help is appreciated. Thanks.
Here's the main part:
+(UIImage *)tintedImageFromImage:(UIImage *)sourceImage colour:(UIColor *)color intensity:(float)intensity {
if (UIGraphicsBeginImageContextWithOptions != NULL) {
UIGraphicsBeginImageContextWithOptions(sourceImage.size, NO, 0.0);
} else {
UIGraphicsBeginImageContext(sourceImage.size);
}
CGContextRef context = UIGraphicsGetCurrentContext();
CGRect rect = CGRectMake(0, 0, sourceImage.size.width, sourceImage.size.height);
// draw alpha-mask
CGContextSetBlendMode(context, kCGBlendModeNormal);
CGContextDrawImage(context, rect, sourceImage.CGImage);
// draw tint color, preserving alpha values of original image
CGContextSetBlendMode(context, kCGBlendModeSourceIn);
[color setFill];
CGContextFillRect(context, rect);
//Set the original greyscale template as the overlay of the new image
sourceImage = [self verticallyFlipImage:sourceImage];
[sourceImage drawInRect:CGRectMake(0,0, sourceImage.size.width,sourceImage.size.height) blendMode:kCGBlendModeMultiply alpha:intensity];
UIImage *colouredImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
colouredImage = [self verticallyFlipImage:colouredImage];
return colouredImage;
}
this is used to flip the image:
+(UIImage *)verticallyFlipImage:(UIImage *)originalImage {
UIImageView *tempImageView = [[UIImageView alloc] initWithImage:originalImage];
UIGraphicsBeginImageContext(tempImageView.frame.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, tempImageView.frame.size.height);
CGContextConcatCTM(context, flipVertical);
[tempImageView.layer renderInContext:context];
UIImage *flippedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return flippedImage;
}
Add to verticallyFlipImage the line tempImageView.image = nil; in order to make the image view release the image. This solves the problem.
In the drawrect function of a UIView I use CGContext to draw some shapes. This Works fine, I can see my shapes.
Now I'm trying to save what has been drawn on the view as a png on disk. I've read various docs / articles but nothing gets saved. Im testing on the simulator for ios 4.3.
Edit 1
I changed my code and uncommented the context part. I can save the png but it is blank.
- (void)drawRect:(CGRect)rect
{
CGContextRef ctx= UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(ctx, 0, 0, 0, .5);
CGContextBeginPath(ctx);
CGContextAddPath(ctx, mutatablepath);
//CGContextStrokePath(ctx);
CGContextFillPath(ctx);
CFRelease(mutatablepath);
NSString *path0;
NSArray *paths0=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
path0=[[paths0 objectAtIndex:0]stringByAppendingPathComponent:#"images"];
NSError *error;
if (![[NSFileManager defaultManager]fileExistsAtPath:path0]) {
if(![[NSFileManager defaultManager]createDirectoryAtPath:path0 withIntermediateDirectories:NO attributes:nil error:&error])
{
NSLog(#"Create directory error %#",error);
}
}
UIGraphicsBeginImageContext(self.bounds.size);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image=UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *imagedata=UIImagePNGRepresentation(image);
NSString *namepath=[NSString stringWithFormat:#"%#.png",#"test"];
NSString *path;
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
path=[[paths objectAtIndex:0]stringByAppendingPathComponent:#"images"];
NSString *savepath=[NSString stringWithFormat:#"%#/%#",path,namepath ];
// NSError
NSLog(#"%#",savepath);
[imagedata writeToFile:savepath atomically:YES];
}
You can do so by taking the image saving code out of your drawRect method, since the renderInContext method implicitly calls drawRect as necessary:
UIView *myView = [[MyViewClass alloc] initWithFrame:CGRectMake(/*...*/)];
UIGraphicsBeginImageContext(myView.bounds.size);
[myView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Source: http://pastie.org/244916
I'm working on an Acne app in which I have to choose image from UIImagePicker and after adding subViews to it I want to save it in camera roll.
Problem: If I add UIImageView as a subView to the superView, the pickerImage does not save with subView.
And if I add that UIImage as subView to the Picker Image, I am unable to move the added UIImage Views.
I am using the following code for saving images:
-(IBAction)savePhoto
{
NSParameterAssert(imgToDisplayFromPicker.image);
UIImageWriteToSavedPhotosAlbum(imgToDisplayFromPicker.image, nil, nil, nil);
}
Finally Found the Solution :
CGRect contextRect = CGRectMake(6, 6, 302, 230);
UIGraphicsBeginImageContext(contextRect.size);
[self.view.layer renderInContext : UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGImageRef imageRef = CGImageCreateWithImageInRect([viewImage CGImage], contextRect);
UIImage * newImage = [UIImage imageWithCGImage:imageRef scale:1.0 orientation:viewImage.imageOrientation];
UIImageWriteToSavedPhotosAlbum(newImage, nil, nil, nil);
Hi Could you please let me know how to change the default colour of a tababar in Xcode i hav already tried this :
(void)viewDidLoad {
[super viewDidLoad];
UIImageView *img = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"UITabBar.png"]];
img.frame = CGRectOffset(img.frame, 0, 1);
[tabBar1 insertSubview:img atIndex:0];
[img release];
but it doesnt work for me so can you please tel me in detail how can i change the colo
I know, this is an old thread, but nonetheless for all of you looking for an answer.
One of the ways to customize the look of UITabBar is to override drawRect: method with use of categories. Choose to create new file in your Xcode project, choose Objective-C category, then type UITabBar for Category On textfield. Next, declare drawRect: method in your category .h file and implement it in category .m file like this:
- (void)drawRect:(CGRect)rect {
UIImage *img = [UIImage imageNamed: #"tabbarBackground"];
[img drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
This will change the looks of all UITabBar instances in your app.
Hope this helps.