Set Layer Content to UIImage inside a CALayer subclass - not working - iphone

I'm trying to display a UIImage selected from a UIImagePickerController inside a subclass of CALayer and add it to my superview but I can't get it to work.
This is how I Get the Image from the UIImagePickerController, which seems to work good :
- (IBAction)importImage:(id)sender
{
UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
imagePickerController.delegate = self;
imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:imagePickerController];
[popover setPopoverContentSize:CGSizeMake(320,320)];
[popover presentPopoverFromRect:importBackgroundButton.frame inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
self.popoverController = popover;
[imagePickerController release];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[self.popoverController dismissPopoverAnimated:YES];
UIImage* img = [info objectForKey:UIImagePickerControllerOriginalImage];
[[context currentDrawing] setBkgImage:img];
}
This is my subclass of CALayer which contains the UIImage to display :
#interface UI_BackgroundImageLayer : CALayer
{
//This is for the Import image as background feature
UIImage* _bkgImg;
}
#property (nonatomic, retain) UIImage* _bkgImg;
-(void)update:(UIImage*)src;
#end
////
#implementation UI_BackgroundImageLayer
- (id)init
{
self = [ super init ];
// [self resetTransform ];
_bkgImg = nil;
return self;
}
-(void)update:(UIImage*)src
{
_bkgImg = [[UIImage alloc] initWithCGImage:src.CGImage];
self.contentsGravity = kCAGravityResizeAspect;
self.contents = (id)_bkgImg.CGImage;
}
#end
I update the content of the CALayer when the user select another image !
The CALayer is added to the superview from start like this :
[[_superView layer] insertSublayer:context._imgLayer atIndex:0];
It's inserted at index 0 because it's meant to be a background image so it must be under other UI elements and drawings.
All of this seems good to me, but nothing appears on the screen ...

Are you using XCode v4.2? If so, this may be relevant to you or it may not but it's worth a look. I've had exacty the same problem as you with CALayer subclasses not responding to the usual display methods (like setCornerRadius, setBackgroundColor etc...). Try this; in your hosting view, just after you've instanced the VIEW put the following line;
[self setBackgroundColor [UIColor clearColor]];
You may well find that from that point on, your layer subclass works perfectly.
My view subclass code looks like this;
// layerClass
+ (Class) layerClass {
return [myLayerSubclass class];
}
// View subclass init routine
- (id) initWithFrame: (CGRect) p_frame {
self = [super initWithFrame: p_frame];
if (self) {
[self setBackgroundColor: [UIColor clearColor]]; // *** BUG WORKARUND? *** Note: Do Apple know about this?
// Rest of your view init ....
}
return self;
}
It seems that the layer subclass does not respond until its hosting view has 'acknowledged' that it's there. It took me days to debug but now all my code works perfectly.
Hope this helps.
V.V.

Related

iOS - Invert a UIImage with button

I have a simple application where I can take an photo or choose and existing photo on the camera roll and then display the image in a UIImageView. I want to have a button that you can press and invert the picked image and then display that in the camera roll. My question is, how do invert the colors of a UIImage and then use the new inverted one to display in the ImageView? I have seen other posts related to this but none explain how implement the code. I'm fairly new to xcode and would appreciate all feedback.
Here is my .m file for the view controller:
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize imageView;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(IBAction)takePhoto {
picker1 = [[UIImagePickerController alloc] init];
picker1.delegate = self;
[picker1 setSourceType:UIImagePickerControllerSourceTypeCamera];
[self presentViewController:picker1 animated:YES completion:nil];
}
-(IBAction)ChooseExisting {
picker2 = [[UIImagePickerController alloc] init];
picker2.delegate = self;
[picker2 setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[self presentViewController:picker2 animated:YES completion:nil];
}
-(IBAction)invertImage {
}
-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
imageFinal = [info objectForKey:UIImagePickerControllerOriginalImage];
[imageView setImage:imageFinal];
[self dismissViewControllerAnimated:YES completion:nil];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[self dismissViewControllerAnimated:YES completion:nil];
}
#end
I see the negetiveImage method has a lot of code. Here's a simple one using Core Image filters.
Include Core Image Framework to your project
Import the core Image header.
#import <CoreImage/CoreImage.h>
The below code should return you the inverted UIImage
UIImage *inputImage = [UIImage imageNamed:#"imageName"];
CIFilter* filter = [CIFilter filterWithName:#"CIColorInvert"];
[filter setDefaults];
[filter setValue:inputImage.CIImage forKey:#"inputImage"];
UIImage *outputImage = [[UIImage alloc] initWithCIImage:filter.outputImage];
The outputImage will be inverted
To give you an easy answer, you can invert the UIImageView which has your UIImage.
To invert it, just use
[yourImageView setTransform:CGAffineTransformMakeScale(-1, 1)]; // flip horizontally
[yourImageView setTransform:CGAffineTransformMakeScale(1, -1)]; // flip vertically
[yourImageView setTransform:CGAffineTransformMakeScale(-1, -1)]; // flip horizontally and vertically
and to bring it back to normal, use
[yourImageView setTransform:CGAffineTransformIdentity]; // bring the view back to normal.
Hope this helps and I wish you all the best with you app :)

Updating Button image once is selected iPad not working

I am trying to make my image update once a new on is selected.
The update works but it does not show up right away when the new image is selected during editing and I was wondering if anyone has any idea how to fix it.
The app was originally created for iPhone and this function works fine, the image is updated as soon as a new one is selected even during editing for the iPhone, but when I use it on the iPad the image does not change during editing but once I finish the editing and go back, I can see the image is change.
I am making the core data recipe sample code from the developer center to work on the iPad.
This is my code for selecting a new Image PhotoTapped1 button, this has been change to work with the iPad:
- (IBAction)photoTapped1 {
if(UI_USER_INTERFACE_IDIOM()== UIUserInterfaceIdiomPhone){
// If in editing state, then display an image picker; if not, create and push a photo view controller.
if (self.editing) {
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
[self presentViewController:imagePicker animated:YES completion:nil];
[imagePicker release];
} else {
RecipePhotoViewController *recipePhotoViewController = [[RecipePhotoViewController alloc] init];
recipePhotoViewController.hidesBottomBarWhenPushed = YES;
recipePhotoViewController.recipe = recipe;
[self.navigationController pushViewController:recipePhotoViewController animated:YES];
[recipePhotoViewController release];
}
}else{
if (self.editing){
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
self.popover = [[UIPopoverController alloc] initWithContentViewController:imagePicker];
[self.popover presentPopoverFromRect:CGRectMake(0, 0, 400, 400) inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
self.popover.delegate = self;
[popover release];
}else{
RecipePhotoViewController *recipePhotoViewController = [[RecipePhotoViewController alloc] init];
recipePhotoViewController.hidesBottomBarWhenPushed = YES;
recipePhotoViewController.recipe = recipe;
[self.navigationController pushViewController:recipePhotoViewController animated:YES];
[recipePhotoViewController release];
}}}
This is working fine and the image is update on, but not during editing.
During editing it shows the image that was there all along, so it can be confusing as anyone using the app can not be sure if the new selected image has been added or updated.
The following is the imagePickerController and the updateButton code:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)selectedImage editingInfo:(NSDictionary *)editingInfo {
// Delete any existing image.
NSManagedObject *oldImage = recipe.image;
if (oldImage != nil) {
[recipe.managedObjectContext deleteObject:oldImage];
}
// Create an image object for the new image.
NSManagedObject *image = [NSEntityDescription insertNewObjectForEntityForName:#"Image" inManagedObjectContext:recipe.managedObjectContext];
recipe.image = image;
// Set the image for the image managed object.
[image setValue:selectedImage forKey:#"image"];
// Create a thumbnail version of the image for the recipe object.
CGSize size = selectedImage.size;
CGFloat ratio = 0;
if (size.width > size.height) {
ratio = 44.0 / size.width;
} else {
ratio = 44.0 / size.height;
}
CGRect rect = CGRectMake(0.0, 0.0, ratio * size.width, ratio * size.height);
UIGraphicsBeginImageContext(rect.size);
[selectedImage drawInRect:rect];
recipe.thumbnailImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[self dismissModalViewControllerAnimated:YES];}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[self dismissViewControllerAnimated:YES completion: nil];
}
Here is the updatePhotoButton:
- (void)updatePhotoButton {
/* How to present the photo button depends on the editing state and whether the recipe has a thumbnail image.
* If the recipe has a thumbnail, set the button's highlighted state to the same as the editing state (it's highlighted if editing).
* If the recipe doesn't have a thumbnail, then: if editing, enable the button and show an image that says "Choose Photo" or similar; if not editing then disable the button and show nothing.
*/
BOOL editing = self.editing;
if (recipe.thumbnailImage != nil) {
photoButton.highlighted = editing;
} else {
photoButton.enabled = editing;
if (editing) {
[photoButton setImage:[UIImage imageNamed:#"choosePhoto.png"] forState:UIControlStateNormal];
} else {
[photoButton setImage:nil forState:UIControlStateNormal];
}
}
}
Does anyone has any idea what would be the problem? I know the UIImagePickerControll has to be used with UIPopoverController in order to work on the iPad, but that is being updated on the -(IBAction)PhotoTapped1 code.
Not sure where to go from here.
Thank you.
Update to question..
PhotoViewController.h
#class Recipe;
#interface RecipePhotoViewController : UIViewController {
#private
Recipe *recipe;
UIImageView *imageView;
}
#property(nonatomic, retain) Recipe *recipe;
#property(nonatomic, retain) UIImageView *imageView;
#end
RecipePhotoViewController.m
#import "RecipePhotoViewController.h"
#import "Recipe.h"
#implementation RecipePhotoViewController
#synthesize recipe;
#synthesize imageView;
- (void)loadView {
self.title = #"Photo";
imageView = [[UIImageView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame];
imageView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.backgroundColor = [UIColor blackColor];
self.view = imageView;
}
- (void)viewWillAppear:(BOOL)animated {
imageView.image = [recipe.image valueForKey:#"image"];
}
- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (void)dealloc {
[imageView release];
[recipe release];
[super dealloc];
}
#end
This is an updated data to original question
The reason there's no problem on iPhone is that the previous image isn't visible on iPhone, because you're using a presented view controller: the image picker takes over the entire screen. On iPad, on the other hand, you're using a popover, so the main interface is still visible behind the popover. Thus the user is able to see that the image being tapped is not the image that appears back in the main interface.
But might argue that there's no problem with this. The user hasn't actually accepted the image yet, until the image picker popover is dismissed. You say:
During editing it shows the image that was there all along, so it can be confusing as anyone using the app can not be sure if the new selected image has been added or updated.
But what if the user taps outside the popover to dismiss / cancel it? Surely you wouldn't want the image to have changed in the main interface. The behavior you're objecting to, therefore, is right: you're complaining that the image in the main interface is not updated until the popover is actually dismissed, and that's exactly how it should be. When the user is working in a popover, what's going on behind the popover is irrelevant.

UIImagePickerController having issues even after declaring from the Appdelegate

we are doing a photo application in which UIImagePickerController is used. For maintaining only one instance of the controller we have declared it in the appdelegate. But even after doing that memory leak is still there. Can any one please help us
Here's our code
In AppDelegate.h
UIImagePickerController *imagePicker;
#property (nonatomic, retain) UIImagePickerController *imagePicker;
In AppDelegate.m
#synthesize imagePicker;
and in applicationDidFinishLaunching event
imagePicker = [[[UIImagePickerController alloc] init] autorelease];
Need to call this UIImagePicker in CameraView
In CameraView.h
RedDawnMediaAppDelegate *appDel;
#property (nonatomic, retain) RedDawnMediaAppDelegate *appDel;
In CameraView.m
#synthesize appDel;
and in viewDidLoad
appDel=(RedDawnMediaAppDelegate*)[[UIApplication sharedApplication] delegate];
appDel.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
// Hide the camera controls:
appDel.imagePicker.showsCameraControls = NO;
appDel.imagePicker.navigationBarHidden = YES;
appDel.imagePicker.delegate = self;
// Make the view full screen:
appDel.imagePicker.wantsFullScreenLayout = YES;
appDel.imagePicker.cameraViewTransform = CGAffineTransformScale(appDel.imagePicker.cameraViewTransform, CAMERA_TRANSFORM_X, CAMERA_TRANSFORM_Y);
// Now incert our overlay view (it has to be here cuz it's a modal view):
appDel.imagePicker.cameraOverlayView = overlayView;
[self presentModalViewController:appDel.imagePicker animated:YES];
in didFinishPickingMediaWithInfo
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[appDelegate.imagePicker dismissModalViewControllerAnimated:YES];
uploadImage = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
[uploadImage retain];
NSData *imageData = UIImageJPEGRepresentation(uploadImage, 0.5);
//[uploadImage release];
UIImage *image=[UIImage imageWithData:imageData];
self.view.frame = CGRectMake(0, 0, 320, 480);
self.wantsFullScreenLayout = YES;
objCameraImageView = [[CameraImageView alloc] initWithNibName:#"CameraImageView" bundle:[NSBundle mainBundle]];
[objCameraImageView setParentController:self];
objCameraImageView.cameraImage = image;
[image release];
uploadImage = nil;
[self.view addSubview:objCameraImageView.view];
[self release];
}
After taking a photo we are showing the preview in another view. so we are invoking the Cameraview for several times which is leading to Memory leak pls help.
First of all you dont need to worry about maintaining only one instance of imagepickercontroller. Getting an image from camera is much simpler than what you are doing.
See my post here:
How to take picture from Camera & saved in Photo Gallery by programmatically?
since Im releasing the picker when its done getting the image. There wont be memory leak!

How to add image overlay to UIImagePickerControllerSourceTypePhotoLibrary when editing?

I've tried looking everywhere for an answer to this but can not find any useful info.
Basically, I want the user to pick a picture from the album, and then have the app display the picture in the edit/crop mode.
On this edit screen I want to display an overlay screen for the user to use to align his image.
He then clicks the save button which saves the edited picture with the overlay image by just merging the images.
The only thing I can not find how to do is add the overlay image in the edit screen!
I can do this quite easily when:
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
But when:
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
I can not use:
imagePicker.cameraOverlayView = overlayGraphicView;
and that is my issue.
Also if I add an UIimage as a subview instead then this overlay, it stays on the screen even when the user is choosing his image from the album. I only want the overlay to appear after the image has been chosen for editing and before it has been saved to the album after the editing has finished.
Thanks for your help.
Heres the method:
- (IBAction)pickPhotoButton:(id)sender {
NSLog(#"Pick a Current Photo Button Pressed...");
// Create image picker controller
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
// Set source to the camera
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
// Delegate is self
imagePicker.delegate = self;
// Allow editing of image ?
imagePicker.allowsEditing = YES;
// Show image picker
[self presentModalViewController:imagePicker animated:YES];
}
and heres my save to album method:
// Save the image to photo album
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
// Access the uncropped image from info dictionary
UIImage *image = [info objectForKey:#"UIImagePickerControllerEditedImage"];
// Combine image with overlay before saving!!
image = [self addOverlayToImage:image];
// Save image
UIImageWriteToSavedPhotosAlbum(image, self, #selector(image:didFinishSavingWithError:contextInfo:), nil);
[picker release];
}
You can become UIImagePickerController object's delegate and keenly observe the UINavigationControllerDelegate methods - navigationController:didShowViewController:animated: and navigationController:willShowViewController:animated:. You can know when the second view controller is coming on and later add your overlay to the view controller's view. Sample usage is shown below –
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
if ( [navigationController.viewControllers count] == 2 ) {
overlayView.center = CGPointMake(135, 135);
overlayView.bounds = CGRectZero;
[viewController.view addSubview:overlayView];
[UIView beginAnimations:#"animateTableView" context:nil];
[UIView setAnimationDuration:0.4];
[overlayView setFrame:CGRectMake( 50, 50, 220, 220)];
[UIView commitAnimations];
}
}
You can use the following customised method for adding overlays to the Imagepickercontroller
In yourclassname .h file define
#property (nonatomic, retain) UIImagePickerController* m_Pickercontroller;
#property(nonatomic,retain) UIView *cameraOverlayView;
In yourclassname.m file
-(void)Loadcaptureview
{
//Allocating Image Picker Controller
m_Pickercontroller=[[UIImagePickerController alloc] init ];
m_Pickercontroller.delegate=self;
m_Pickercontroller.allowsEditing=YES;
m_Pickercontroller.sourceType=UIImagePickerControllerSourceTypeCamera;
m_Pickercontroller.view.frame=CGRectMake(0, 0, 320, 300);
UIButton*Clickbutton=[[UIButton alloc] initWithFrame:CGRectMake(50,200, 60, 60)];
[Clickbutton setImage:[UIImage imageNamed:#"red-circle-button.png"] forState:UIControlStateNormal];
[Clickbutton addTarget:self action:#selector(clicked:) forControlEvents:UIControlEventTouchUpInside];
image1=[[UIImageView alloc] initWithFrame:CGRectMake(50,400, 60, 60)];
image1.image=[UIImage imageNamed:#"red-circle-button.png"];
[m_Pickercontroller.cameraOverlayView addSubview:Clickbutton];
[m_Pickercontroller.cameraOverlayView addSubview:image1];
[m_Pickercontroller.cameraOverlayView bringSubviewToFront:image1];
//Hiding the Camera Control
m_Pickercontroller.showsCameraControls=NO;
//Presenting the imagepicker Controller to Present Modal view Controller
[self.navigationController presentModalViewController:m_Pickercontroller animated:YES];
}
// Calling the Function
- (void)viewDidLoad
{
[self Loadcaptureview];
}

After creating a UIView with initWithFrame, how do I change the image?

I'm a bit lost here. I have a class subclassed from UIView called BalloonGuy. I initialize it like this.
- (id)initWithFrame:(CGRect)frame {
UIImage* loadedImage = [UIImage imageNamed:#"balloonguy.png"];
CGRect rect = CGRectMake(0, 0, loadedImage.size.width, loadedImage.size.height);
self = [super initWithFrame:rect];
image=[loadedImage retain];
self.opaque = YES;
self.backgroundColor = [UIColor clearColor];
return self;
}
I add it as a subview and everything is great.
What I can't do, however is change the image afterwards, ever. I won't list my failed attempts but what do I do?
I think you'll need to redraw your view when you change your image property, so overriding the property setter in this case may be a good idea:
- (void) setImage:(UIImage *) im {
[image release];
image = nil;
image = [im retain];
[self setNeedsLayout];
}