some rethinking of initial menu presentation and initial orientation (also merging images should be threadsafe now)
authorkoda
Sun, 10 Oct 2010 22:32:01 +0200
changeset 3948 24daa33a3114
parent 3947 709fdb89f76c
child 3949 4c4c0a2507cc
some rethinking of initial menu presentation and initial orientation (also merging images should be threadsafe now)
hedgewars/PascalExports.pas
hedgewars/uMobile.pas
project_files/HedgewarsMobile/Classes/GameConfigViewController.h
project_files/HedgewarsMobile/Classes/GameConfigViewController.m
project_files/HedgewarsMobile/Classes/GameSetup.m
project_files/HedgewarsMobile/Classes/HogButtonView.m
project_files/HedgewarsMobile/Classes/HogHatViewController.m
project_files/HedgewarsMobile/Classes/OverlayViewController.m
project_files/HedgewarsMobile/Classes/PascalImports.h
project_files/HedgewarsMobile/Classes/SingleTeamViewController.m
project_files/HedgewarsMobile/Classes/UIImageExtra.h
project_files/HedgewarsMobile/Classes/UIImageExtra.m
--- a/hedgewars/PascalExports.pas	Sun Oct 10 21:32:18 2010 +0400
+++ b/hedgewars/PascalExports.pas	Sun Oct 10 22:32:01 2010 +0200
@@ -167,18 +167,6 @@
     if closeFrontend then alsoShutdownFrontend:= true;
 end;
 
-procedure HW_setLandscape(landscape: boolean); cdecl; export;
-begin
-    if landscape then
-    begin
-        cOffsetY:= 0;
-    end
-    else
-    begin
-        cOffsetY:= 120;
-    end;
-end;
-
 procedure HW_setCursor(x,y: LongInt); cdecl; export;
 begin
     CursorPoint.X:= x;
--- a/hedgewars/uMobile.pas	Sun Oct 10 21:32:18 2010 +0400
+++ b/hedgewars/uMobile.pas	Sun Oct 10 22:32:01 2010 +0200
@@ -31,19 +31,19 @@
 procedure updateVisualsNewTurn; cdecl; external;
 function  isApplePhone: Boolean; cdecl; external;
 {$ENDIF}
-function  isPhone: Boolean;
-procedure doRumble;
-procedure perfExt_AddProgress;
-procedure perfExt_FinishProgress;
-procedure perfExt_AmmoUpdate;
-procedure perfExt_NewTurnBeginning;
-procedure perfExt_SaveBeganSynching;
-procedure perfExt_SaveFinishedSynching;
+function  isPhone: Boolean; inline;
+procedure doRumble; inline;
+procedure perfExt_AddProgress; inline;
+procedure perfExt_FinishProgress; inline;
+procedure perfExt_AmmoUpdate; // don't inline
+procedure perfExt_NewTurnBeginning; inline;
+procedure perfExt_SaveBeganSynching; inline;
+procedure perfExt_SaveFinishedSynching; inline;
 
 implementation
 uses uTeams;
 
-function isPhone: Boolean;
+function isPhone: Boolean; inline;
 begin
 {$IFDEF IPHONEOS}
     exit(isApplePhone());
@@ -51,26 +51,26 @@
     exit(false);
 end;
 
-procedure doRumble;
+procedure doRumble; inline;
 begin
     // fill me!
 end;
 
-procedure perfExt_AddProgress;
+procedure perfExt_AddProgress; inline;
 begin
 {$IFDEF IPHONEOS}
     startSpinning();
 {$ENDIF}
 end;
 
-procedure perfExt_FinishProgress;
+procedure perfExt_FinishProgress; inline;
 begin
 {$IFDEF IPHONEOS}
     stopSpinning();
 {$ENDIF}
 end;
 
-procedure perfExt_AmmoUpdate;
+procedure perfExt_AmmoUpdate; // don't inline
 begin
 {$IFDEF IPHONEOS}
     if (CurrentTeam^.ExtDriven) or (CurrentTeam^.Hedgehogs[0].BotLevel <> 0) then
@@ -79,22 +79,22 @@
 {$ENDIF}
 end;
 
-procedure perfExt_NewTurnBeginning;
+procedure perfExt_NewTurnBeginning; inline;
 begin
 {$IFDEF IPHONEOS}
     clearView();
-    updateVisualsNewTurn();
+    perfExt_AmmoUpdate();
 {$ENDIF}
 end;
 
-procedure perfExt_SaveBeganSynching;
+procedure perfExt_SaveBeganSynching; inline;
 begin
 {$IFDEF IPHONEOS}
     replayBegan();
 {$ENDIF}
 end;
 
-procedure perfExt_SaveFinishedSynching;
+procedure perfExt_SaveFinishedSynching; inline;
 begin
 {$IFDEF IPHONEOS}
     replayFinished();
--- a/project_files/HedgewarsMobile/Classes/GameConfigViewController.h	Sun Oct 10 21:32:18 2010 +0400
+++ b/project_files/HedgewarsMobile/Classes/GameConfigViewController.h	Sun Oct 10 22:32:01 2010 +0200
@@ -27,7 +27,6 @@
 @class SchemeWeaponConfigViewController;
 
 @interface GameConfigViewController : UIViewController {
-    UIImage *hedgehogImage;
     UIView *imgContainer;
     HelpPageViewController *helpPage;
     
@@ -36,8 +35,7 @@
     SchemeWeaponConfigViewController *schemeWeaponConfigViewController;
 }
 
-@property (nonatomic,retain) UIImage *hedgehogImage;
-@property (nonatomic,retain) UIView *imgContainer;
+@property (retain) UIView *imgContainer;
 @property (nonatomic,retain) HelpPageViewController *helpPage;
 @property (nonatomic,retain) MapConfigViewController *mapConfigViewController;
 @property (nonatomic,retain) TeamConfigViewController *teamConfigViewController;
--- a/project_files/HedgewarsMobile/Classes/GameConfigViewController.m	Sun Oct 10 21:32:18 2010 +0400
+++ b/project_files/HedgewarsMobile/Classes/GameConfigViewController.m	Sun Oct 10 22:32:01 2010 +0200
@@ -30,7 +30,7 @@
 #import "PascalImports.h"
 
 @implementation GameConfigViewController
-@synthesize hedgehogImage, imgContainer, helpPage, mapConfigViewController, teamConfigViewController, schemeWeaponConfigViewController;
+@synthesize imgContainer, helpPage, mapConfigViewController, teamConfigViewController, schemeWeaponConfigViewController;
 
 
 -(BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
@@ -202,12 +202,13 @@
                                                                       teamConfigViewController.listOfSelectedTeams,@"teams_list",
                                                                       schemeWeaponConfigViewController.selectedScheme,@"scheme",
                                                                       schemeWeaponConfigViewController.selectedWeapon,@"weapon",
+                                                                      [NSNumber numberWithInt:self.interfaceOrientation],@"orientation",
                                                                       nil];
 
     // finally launch game and remove this controller
     DLog(@"sending config %@", gameDictionary);
 
-    if ([[gameDictionary allKeys] count] == 10) {
+    if ([[gameDictionary allKeys] count] == 11) {
         NSDictionary *allDataNecessary = [NSDictionary dictionaryWithObjectsAndKeys:gameDictionary,@"game_dictionary", @"",@"savefile",
                                                                                     [NSNumber numberWithBool:NO],@"netgame", nil];
         [[SDLUIKitDelegate sharedAppDelegate] startSDLgame:allDataNecessary];
@@ -242,6 +243,37 @@
 
 }
 
+-(void) loadNiceHogs {
+    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
+    NSString *filePath = [NSString stringWithFormat:@"%@/Hedgehog.png",GRAPHICS_DIRECTORY()];
+    UIImage *sprite = [[UIImage alloc] initWithContentsOfFile:filePath andCutAt:CGRectMake(96, 0, 32, 32)];
+    
+    NSArray *hatArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:HATS_DIRECTORY() error:NULL];
+    int numberOfHats = [hatArray count];
+
+    if (self.imgContainer != nil)
+        [self.imgContainer removeFromSuperview];
+    
+    self.imgContainer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 40)];
+    for (int i = 0; i < 1 + random()%40; i++) {
+        NSString *hat = [hatArray objectAtIndex:random()%numberOfHats];
+        
+        NSString *hatFile = [[NSString alloc] initWithFormat:@"%@/%@", HATS_DIRECTORY(), hat];
+        UIImage *hatSprite = [[UIImage alloc] initWithContentsOfFile: hatFile andCutAt:CGRectMake(0, 0, 32, 32)];
+        [hatFile release];
+        UIImage *hogWithHat = [sprite mergeWith:hatSprite atPoint:CGPointMake(0, 5)];
+        [hatSprite release];
+        
+        UIImageView *hog = [[UIImageView alloc] initWithImage:hogWithHat];
+        hog.frame = CGRectMake(10*(i+1)+random()%30, 30, 32, 32);
+        [self.imgContainer addSubview:hog];
+        [hog release];
+    }
+    [self.view addSubview:self.imgContainer];
+    [sprite release];
+    [pool drain];
+}
+
 -(void) viewDidLoad {
     self.view.backgroundColor = [UIColor blackColor];
 
@@ -254,7 +286,6 @@
                                                      name:@"buttonPressed"
                                                    object:nil];
         srandom(time(NULL));
-        self.hedgehogImage = nil;
         
         // load other controllers
         if (self.mapConfigViewController == nil)
@@ -271,48 +302,20 @@
         
     } else {
         // this is the visible controller
-        if (mapConfigViewController == nil)
-            mapConfigViewController = [[MapConfigViewController alloc] initWithNibName:@"MapConfigViewController-iPhone" bundle:nil];
-        // this must be loaded & added to auto set default scheme and ammo
-        schemeWeaponConfigViewController = [[SchemeWeaponConfigViewController alloc] initWithStyle:UITableViewStyleGrouped];
-        [self.view addSubview:schemeWeaponConfigViewController.view];
+        if (self.mapConfigViewController == nil)
+            self.mapConfigViewController = [[MapConfigViewController alloc] initWithNibName:@"MapConfigViewController-iPhone" bundle:nil];
+        // this must be loaded & added in order to auto set default scheme and ammo
+        self.schemeWeaponConfigViewController = [[SchemeWeaponConfigViewController alloc] initWithStyle:UITableViewStyleGrouped];
+        [self.view addSubview:self.schemeWeaponConfigViewController.view];
     }
-    [self.view addSubview:mapConfigViewController.view];
+    [self.view addSubview:self.mapConfigViewController.view];
 
     [super viewDidLoad];
 }
 
 -(void) viewWillAppear:(BOOL)animated {
-    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
-        // load a base image that will be updated in viewWill Load
-        if (self.hedgehogImage == nil) {
-            NSString *filePath = [NSString stringWithFormat:@"%@/Hedgehog.png",GRAPHICS_DIRECTORY()];
-            UIImage *sprite = [[UIImage alloc] initWithContentsOfFile:filePath andCutAt:CGRectMake(96, 0, 32, 32)];
-            self.hedgehogImage = sprite;
-            [sprite release];
-        }
-        
-        NSArray *hatArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:HATS_DIRECTORY() error:NULL];
-        int numberOfHats = [hatArray count];
-        if (self.imgContainer == nil)
-            self.imgContainer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 40)];
-        
-        for (int i=0; i < 1 + random()%40; i++) {
-            NSString *hat = [hatArray objectAtIndex:random()%numberOfHats];
-            
-            NSString *hatFile = [[NSString alloc] initWithFormat:@"%@/%@", HATS_DIRECTORY(), hat];
-            UIImage *hatSprite = [[UIImage alloc] initWithContentsOfFile: hatFile andCutAt:CGRectMake(0, 0, 32, 32)];
-            [hatFile release];
-            UIImage *hogWithHat = [self.hedgehogImage mergeWith:hatSprite atPoint:CGPointMake(0, -5)];
-            [hatSprite release];
-            
-            UIImageView *hog = [[UIImageView alloc] initWithImage:hogWithHat];
-            hog.frame = CGRectMake(10*(i+1)+random()%30, 30, 32, 32);
-            [self.imgContainer addSubview:hog];
-            [hog release];
-        }
-        [self.view addSubview:self.imgContainer];
-    }
+    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
+        [NSThread detachNewThreadSelector:@selector(loadNiceHogs) toTarget:self withObject:nil];
 
     [mapConfigViewController viewWillAppear:animated];
     [teamConfigViewController viewWillAppear:animated];
@@ -337,11 +340,6 @@
 }
 
 -(void) viewDidDisappear:(BOOL)animated {
-    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
-        [self.imgContainer removeFromSuperview];
-        releaseAndNil(self.imgContainer);
-    }
-    
     [mapConfigViewController viewDidDisappear:animated];
     [teamConfigViewController viewDidDisappear:animated];
     [schemeWeaponConfigViewController viewDidDisappear:animated];
@@ -361,14 +359,12 @@
 
     // Release any cached data, images, etc that aren't in use.
     self.imgContainer = nil;
-    self.hedgehogImage = nil;
     MSG_MEMCLEAN();
     [super didReceiveMemoryWarning];
 }
 
 -(void) viewDidUnload {
-    [[NSNotificationCenter defaultCenter] removeObserver:self forKeyPath:@"buttonPressed"];
-    self.hedgehogImage = nil;
+    [[NSNotificationCenter defaultCenter] removeObserver:self];
     self.imgContainer = nil;
     self.mapConfigViewController = nil;
     self.teamConfigViewController = nil;
@@ -379,7 +375,6 @@
 }
 
 -(void) dealloc {
-    [hedgehogImage release];
     [imgContainer release];
     [mapConfigViewController release];
     [teamConfigViewController release];
--- a/project_files/HedgewarsMobile/Classes/GameSetup.m	Sun Oct 10 21:32:18 2010 +0400
+++ b/project_files/HedgewarsMobile/Classes/GameSetup.m	Sun Oct 10 22:32:01 2010 +0200
@@ -35,19 +35,24 @@
     if (self = [super init]) {
         ipcPort = randomPort();
 
-        // should check they exist and throw and exection if not
+        // the general settings file + menu style (read by the overlay)
         NSDictionary *dictSett = [[NSDictionary alloc] initWithContentsOfFile:SETTINGS_FILE()];
+        self.menuStyle = [[dictSett objectForKey:@"menu"] boolValue];
         self.systemSettings = dictSett;
-        self.menuStyle = [[dictSett objectForKey:@"menu"] boolValue];
         [dictSett release];
 
+        // this game run settings
         self.gameConfig = [gameDictionary objectForKey:@"game_dictionary"];
+
+        // is it a netgame?
         isNetGame = [[gameDictionary objectForKey:@"netgame"] boolValue];
+
+        // is it a Save?
         NSString *path = [gameDictionary objectForKey:@"savefile"];
-        // if path is empty it means i have to create a new file, otherwise i read from that file
+        // if path is empty it means that you have to create a new file, otherwise read from that file
         if ([path isEqualToString:@""] == YES) {
             NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
-            [outputFormatter setDateFormat:@"yyyy-MM-dd 'at' HH,mm"];
+            [outputFormatter setDateFormat:@"yyyy.MM.dd '@' HH-mm"];
             NSString *newDateString = [outputFormatter stringFromDate:[NSDate date]];
             self.savePath = [SAVES_DIRECTORY() stringByAppendingFormat:@"%@.hws", newDateString];
             [outputFormatter release];
@@ -451,7 +456,12 @@
         CGRect screenBounds = [[UIScreen mainScreen] bounds];
         width = (int) screenBounds.size.height;
         height = (int) screenBounds.size.width;
-        rotation = @"-90";
+        UIDeviceOrientation orientation = (UIDeviceOrientation) [[self.gameConfig objectForKey:@"orientation"] intValue];
+        if (orientation == UIDeviceOrientationLandscapeLeft)
+            rotation = @"-90";
+        else
+            rotation = @"90";
+
     }
         
     NSString *horizontalSize = [[NSString alloc] initWithFormat:@"%d", width];
--- a/project_files/HedgewarsMobile/Classes/HogButtonView.m	Sun Oct 10 21:32:18 2010 +0400
+++ b/project_files/HedgewarsMobile/Classes/HogButtonView.m	Sun Oct 10 22:32:01 2010 +0200
@@ -66,7 +66,7 @@
         for (int i = 0; i < numberOfHogs; i++) {
             teamHogs = [singleHog mergeWith:teamHogs
                                     atPoint:CGPointMake(8, 0)
-                                     atSize:CGSizeMake(88, 32)];
+                                     ofSize:CGSizeMake(88, 32)];
         }
         [self setImage:teamHogs forState:UIControlStateNormal];
     }
--- a/project_files/HedgewarsMobile/Classes/HogHatViewController.m	Sun Oct 10 21:32:18 2010 +0400
+++ b/project_files/HedgewarsMobile/Classes/HogHatViewController.m	Sun Oct 10 22:32:01 2010 +0200
@@ -31,7 +31,6 @@
     return rotationManager(interfaceOrientation);
 }
 
-
 #pragma mark -
 #pragma mark View lifecycle
 - (void)viewDidLoad {
@@ -88,7 +87,7 @@
     NSString *hatFile = [[NSString alloc] initWithFormat:@"%@/%@", HATS_DIRECTORY(), hat];
     UIImage *hatSprite = [[UIImage alloc] initWithContentsOfFile: hatFile andCutAt:CGRectMake(0, 0, 32, 32)];
     [hatFile release];
-    cell.imageView.image = [self.normalHogSprite mergeWith:hatSprite atPoint:CGPointMake(0, -5)];
+    cell.imageView.image = [self.normalHogSprite mergeWith:hatSprite atPoint:CGPointMake(0, 5)];
     [hatSprite release];
 
     if ([hat isEqualToString:[hog objectForKey:@"hat"]]) {
--- a/project_files/HedgewarsMobile/Classes/OverlayViewController.m	Sun Oct 10 21:32:18 2010 +0400
+++ b/project_files/HedgewarsMobile/Classes/OverlayViewController.m	Sun Oct 10 22:32:01 2010 +0200
@@ -63,32 +63,12 @@
             if (IS_DUALHEAD() == NO)
                 sdlView.transform = CGAffineTransformMakeRotation(degreesToRadians(0));
             self.view.transform = CGAffineTransformMakeRotation(degreesToRadians(90));
-            HW_setLandscape(YES);
             break;
         case UIDeviceOrientationLandscapeRight:
             if (IS_DUALHEAD() == NO)
                 sdlView.transform = CGAffineTransformMakeRotation(degreesToRadians(180));
             self.view.transform = CGAffineTransformMakeRotation(degreesToRadians(-90));
-            HW_setLandscape(YES);
             break;
-        /*
-        case UIDeviceOrientationPortrait:
-            if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
-                sdlView.transform = CGAffineTransformMakeRotation(degreesToRadian(270));
-                self.view.transform = CGAffineTransformMakeRotation(degreesToRadian(0));
-                [self chatAppear];
-                HW_setLandscape(NO);
-            }
-            break;
-        case UIDeviceOrientationPortraitUpsideDown:
-            if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
-                sdlView.transform = CGAffineTransformMakeRotation(degreesToRadian(90));
-                self.view.transform = CGAffineTransformMakeRotation(degreesToRadian(180));
-                [self chatAppear];
-                HW_setLandscape(NO);
-            }
-            break;
-        */
         default:
             // a debug log would spam too much
             break;
@@ -112,25 +92,7 @@
     self.view.center = CGPointMake(self.view.frame.size.height/2.0, self.view.frame.size.width/2.0);
 
     initialScreenCount = [[UIScreen screens] count];
-    
-    // set initial orientation wrt the controller orientation
-    UIDeviceOrientation orientation = self.interfaceOrientation;
-    UIView *sdlView = [[[UIApplication sharedApplication] keyWindow] viewWithTag:SDL_VIEW_TAG];
-    switch (orientation) {
-        case UIDeviceOrientationLandscapeLeft:
-            if (IS_DUALHEAD() == NO)
-                sdlView.transform = CGAffineTransformMakeRotation(degreesToRadians(0));
-            self.view.transform = CGAffineTransformMakeRotation(degreesToRadians(90));
-            break;
-        case UIDeviceOrientationLandscapeRight:
-            if (IS_DUALHEAD() == NO)
-                sdlView.transform = CGAffineTransformMakeRotation(degreesToRadians(180));
-            self.view.transform = CGAffineTransformMakeRotation(degreesToRadians(-90));
-            break;
-        default:
-            DLog(@"unknown orientation");
-            break;
-    }
+
     CGRect screenRect = [[UIScreen mainScreen] bounds];
     self.view.frame = CGRectMake(0, 0, screenRect.size.width, screenRect.size.height);
 
--- a/project_files/HedgewarsMobile/Classes/PascalImports.h	Sun Oct 10 21:32:18 2010 +0400
+++ b/project_files/HedgewarsMobile/Classes/PascalImports.h	Sun Oct 10 22:32:01 2010 +0200
@@ -67,7 +67,6 @@
 
     void HW_terminate(BOOL andCloseFrontend);
 
-    void HW_setLandscape(BOOL rotate);
     void HW_setCursor(int x, int y);
     void HW_getCursor(int *x, int *y);
 
--- a/project_files/HedgewarsMobile/Classes/SingleTeamViewController.m	Sun Oct 10 21:32:18 2010 +0400
+++ b/project_files/HedgewarsMobile/Classes/SingleTeamViewController.m	Sun Oct 10 22:32:01 2010 +0200
@@ -221,7 +221,7 @@
             NSString *hatFile = [[NSString alloc] initWithFormat:@"%@/%@.png", HATS_DIRECTORY(), [[hogArray objectAtIndex:row] objectForKey:@"hat"]];
             UIImage *hatSprite = [[UIImage alloc] initWithContentsOfFile: hatFile andCutAt:CGRectMake(0, 0, 32, 32)];
             [hatFile release];
-            editableCell.imageView.image = [self.normalHogSprite mergeWith:hatSprite atPoint:CGPointMake(0, -5)];
+            editableCell.imageView.image = [self.normalHogSprite mergeWith:hatSprite atPoint:CGPointMake(0, 5)];
             [hatSprite release];
 
             editableCell.textField.text = [[hogArray objectAtIndex:row] objectForKey:@"hogname"];
--- a/project_files/HedgewarsMobile/Classes/UIImageExtra.h	Sun Oct 10 21:32:18 2010 +0400
+++ b/project_files/HedgewarsMobile/Classes/UIImageExtra.h	Sun Oct 10 22:32:01 2010 +0200
@@ -26,7 +26,7 @@
  
 -(UIImage *)scaleToSize:(CGSize) size;
 -(UIImage *)mergeWith:(UIImage *)secondImage atPoint:(CGPoint) secondImagePoint;
--(UIImage *)mergeWith:(UIImage *)secondImage atPoint:(CGPoint) secondImagePoint atSize:(CGSize) resultingSize;
+-(UIImage *)mergeWith:(UIImage *)secondImage atPoint:(CGPoint) secondImagePoint ofSize:(CGSize) resultingSize;
 -(id) initWithContentsOfFile:(NSString *)path andCutAt:(CGRect) rect;
 -(UIImage *)cutAt:(CGRect) rect;
 -(UIImage *)convertToGrayScale;
--- a/project_files/HedgewarsMobile/Classes/UIImageExtra.m	Sun Oct 10 21:32:18 2010 +0400
+++ b/project_files/HedgewarsMobile/Classes/UIImageExtra.m	Sun Oct 10 22:32:01 2010 +0200
@@ -45,31 +45,41 @@
 
 -(UIImage *)mergeWith:(UIImage *)secondImage atPoint:(CGPoint) secondImagePoint {
     // create a contex of size of the background image
-    return [self mergeWith:secondImage atPoint:secondImagePoint atSize:self.size];
+    return [self mergeWith:secondImage atPoint:secondImagePoint ofSize:self.size];
 }
 
--(UIImage *)mergeWith:(UIImage *)secondImage atPoint:(CGPoint) secondImagePoint atSize:(CGSize) resultingSize {
+-(UIImage *)mergeWith:(UIImage *)secondImage atPoint:(CGPoint) secondImagePoint ofSize:(CGSize) resultingSize {
     if (secondImage == nil) {
         DLog(@"Warning, secondImage == nil");
         return self;
     }
+    int w = resultingSize.width;
+    int h = resultingSize.height;
+    
+    if (w == 0 || h == 0) {
+        DLog(@"Can have 0 dimesions");
+        return self;
+    }
     
     // Create a bitmap graphics context; this will also set it as the current context
-    UIGraphicsBeginImageContext(resultingSize);
-
-    // draw the background image in the current context
-    [self drawAtPoint:CGPointMake(0,0)];
-
-    // draw the image on top of the first image (because the context is the same)
-    [secondImage drawAtPoint:secondImagePoint];
+    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
+    CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst);
+    
+    // draw the two images in the current context
+    CGContextDrawImage(context, CGRectMake(0, 0, self.size.width, self.size.height), [self CGImage]);
+    CGContextDrawImage(context, CGRectMake(secondImagePoint.x, secondImagePoint.y, secondImage.size.width, secondImage.size.height), [secondImage CGImage]);
+    
+    // Create bitmap image info from pixel data in current context
+    CGImageRef imageRef = CGBitmapContextCreateImage(context);
+    
+    // Create a new UIImage object
+    UIImage *resultImage = [UIImage imageWithCGImage:imageRef];
 
-    // create an image from the current contex (not thread safe)
-    UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
-
-    // free drawing contex
-    UIGraphicsEndImageContext();
-
-    // return the resulting autoreleased image
+    // Release colorspace, context and bitmap information
+    CGColorSpaceRelease(colorSpace);
+    CGContextRelease(context);
+    CFRelease(imageRef);
+   
     return resultImage;
 }
 
@@ -215,13 +225,13 @@
     CGContextSetBlendMode(UIGraphicsGetCurrentContext(), kCGBlendModeDifference);
     CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(),[UIColor whiteColor].CGColor);
     CGContextFillRect(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, self.size.width, self.size.height));
+    // create an image from the current contex (not thread safe)
     UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
     UIGraphicsEndImageContext();
     return result;
 }
 
 +(UIImage *)whiteImage:(CGSize) ofSize {
-    // white rounded rectangle as background image for previewButton
     UIGraphicsBeginImageContext(ofSize);
     CGContextRef context = UIGraphicsGetCurrentContext();
     UIGraphicsPushContext(context);