Objective C: Zoom and Pintch UIImageView

September 2nd, 2009 1 comment

To get started, we have to

1. Create a new project by selecting “Windows-based Application”
2. Create a new UIView using IB and name it ImgView.
3. Create a new file in XCode by selecting File -> New File -> UIViewController sub class and name it “ImgViewController”.
4. In IB, select File’s owner object of the “ImgView” nib file and select Tools -> Identity Inspector. Under Class Identity select “ImgViewContoller” as the class.
5. Select Tools – > Connections Inspector and create a connection from the view property to the view object in IB.
6. Place a UIImageView on the view we just created.
7. Add a image to the resource folder, to be used by the UIImageView.
8. Select the Image and select Tools -> Attributes Inspector in IB. From the Image drop down select your image.
9. Set the Mode to Center.
10. Un-check “User Interaction Enabled” and “Multiple Touch”.
11. Select the view and select “Multiple Touch” in the Attributes Inspector. Note that “User Interaction Enabled” should already be checked, if not check it.

Using the last two settings all the touches events will be sent to ImgViewController. Since we need to control the image, we need a variable of type UIImageView. This is how the header file of “MultiTouchTutorialAppDelegate” will look like.

#import <UIKit/UIKit.h>>
 
@class ImgViewController;
 
@interface MultiTouchTutorialAppDelegate : NSObject {
UIWindow *window;
ImgViewController *ivController;
}
 
@property (nonatomic, retain) IBOutlet UIWindow *window;
 
@end

Using IB, select File’s owner object and open Tools -> Connections Inspector. Create a connection from the imgView to the UIImageView placed on the view. Now we will be able to control the UIImageView from code.

Now we need to add the view “ImgView” as a subview in applicationDidFinishLaunching method. This is how the source code will look like

- (void)applicationDidFinishLaunching:(UIApplication *)application {
 
ivController = [[ImgViewController alloc] initWithNibName:@"ImgView" bundle:[NSBundle mainBundle]];
 
[window addSubview:[ivController view]];
 
// Override point for customization after application launch
[window makeKeyAndVisible];
}

Click on Ctrl+return to run the application in simulator. You should see the image loaded in the simulator.

Right now the application does not respond to any events, but all we have to do is implement some methods. Let’s implement the touchesEnded method which will be called when touches are ended.

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
}

In this method we will respond to a single tap and double tap. On single tap we will zoom out the image and on double tap we will set the mode to “Center”, which is doing the same as in step 9.
This is how the code looks like

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
 
//Get all the touches.
NSSet *allTouches = [event allTouches];
 
//Number of touches on the screen
switch ([allTouches count])
{
case 1:
{
//Get the first touch.
UITouch *touch = [[allTouches allObjects] objectAtIndex:0];
 
switch([touch tapCount])
{
case 1://Single tap
imgView.contentMode = UIViewContentModeScaleAspectFit;
break;
case 2://Double tap.
imgView.contentMode = UIViewContentModeCenter;
break;
}
}
break;
}
 
}

We get all the touches from the event into allTouches variable. We thenfind out how many fingers were touching the screen, since in our case we only want to zoom in and out, it seems normal to assume that the user will only be using one finger. We then find out how many tocuhs are touching the screen by calling the count method of allTouches variable.

If there is only one finger touching the screen, we get the Touch object at index zero and find out the tap count of that object. If the tap count is one we will zoom out the image and if it is two we are going to zoom in. We zoom out the image by setting the contentMode to UIViewContentModeScaleAspectFit and zoom in the image by setting it to UIViewContentModeCenter.

Bookmark and Share
Categories: iPhone SDK Tags: , , , ,

Objective C: Cache Image on iPhone

September 2nd, 2009 No comments

If you’re pulling in web data such as images that doesn’t change but needs to be viewed multiple times, you’ll want to cache it. Caching images dramatically improves the performance of scrolling tables and other views.

Note: this only works for JPG and PNG images. If you have suggestions or find bugs, let me know.

Utilities.h:
Code:

    #import Foundation/Foundation.h
 
    @interface Utilities : NSObject {
 
    }
 
    // Methods
    - (void) cacheImage: (NSString *) ImageURLString;
    - (UIImage *) getCachedImage: (NSString *) ImageURLString;
    - (UIImage *) roundCorners: (UIImage*) img;
 
    @end

Utilities.m
Code:

    #import "Utilities.h"
    #define TMP NSTemporaryDirectory()
 
    @implementation Utilities

Function to actually cache the image – checks to see if one with the same name already exists
Code:

    - (void) cacheImage: (NSString *) ImageURLString
    {
    NSURL *ImageURL = [NSURL URLWithString: ImageURLString];
 
    // Generate a unique path to a resource representing the image you want
    NSString *filename = [[something unique, perhaps the image name]];
    NSString *uniquePath = [TMP stringByAppendingPathComponent: filename];
 
    // Check for file existence
    if(![[NSFileManager defaultManager] fileExistsAtPath: uniquePath])
    {
    // The file doesn't exist, we should get a copy of it
 
    // Fetch image
    NSData *data = [[NSData alloc] initWithContentsOfURL: ImageURL];
    UIImage *image = [[UIImage alloc] initWithData: data];
 
    // Do we want to round the corners?
    image = [self roundCorners: image];
 
    // Is it PNG or JPG/JPEG?
    // Running the image representation function writes the data from the image to a file
    if([ImageURLString rangeOfString: @".png" options: NSCaseInsensitiveSearch].location != NSNotFound)
    {
    [UIImagePNGRepresentation(image) writeToFile: uniquePath atomically: YES];
    }
    else if(
    [ImageURLString rangeOfString: @".jpg" options: NSCaseInsensitiveSearch].location != NSNotFound ||
    [ImageURLString rangeOfString: @".jpeg" options: NSCaseInsensitiveSearch].location != NSNotFound
    )
    {
    [UIImageJPEGRepresentation(image, 100) writeToFile: uniquePath atomically: YES];
    }
    }
    }

Retrieve a cached file:
Code:

  - (UIImage *) getCachedImage: (NSString *) ImageURLString
    {
    NSString *filename = [[something unique, perhaps the image name]];
    NSString *uniquePath = [TMP stringByAppendingPathComponent: filename];
 
    UIImage *image;
 
    // Check for a cached version
    if([[NSFileManager defaultManager] fileExistsAtPath: uniquePath])
    {
    image = [UIImage imageWithContentsOfFile: uniquePath]; // this is the cached image
    }
    else
    {
    // get a new one
    [self cacheImage: ImageURLString];
    image = [UIImage imageWithContentsOfFile: uniquePath];
    }
 
    return image;
    }

These two functions are just to add rounded corners to an image
Code:

 static void addRoundedRectToPath(CGContextRef context, CGRect rect, float ovalWidth, float ovalHeight)
    {
    float fw, fh;
    if (ovalWidth == 0 || ovalHeight == 0)
    {
    CGContextAddRect(context, rect);
    return;
    }
    CGContextSaveGState(context);
    CGContextTranslateCTM (context, CGRectGetMinX(rect), CGRectGetMinY(rect));
    CGContextScaleCTM (context, ovalWidth, ovalHeight);
    fw = CGRectGetWidth (rect) / ovalWidth;
    fh = CGRectGetHeight (rect) / ovalHeight;
    CGContextMoveToPoint(context, fw, fh/2);
    CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 1);
    CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1);
    CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1);
    CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 1);
    CGContextClosePath(context);
    CGContextRestoreGState(context);
    }
 
    - (UIImage *) roundCorners: (UIImage*) img
    {
    int w = img.size.width;
    int h = img.size.height;
 
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst);
 
    CGContextBeginPath(context);
    CGRect rect = CGRectMake(0, 0, img.size.width, img.size.height);
    addRoundedRectToPath(context, rect, 5, 5);
    CGContextClosePath(context);
    CGContextClip(context);
 
    CGContextDrawImage(context, CGRectMake(0, 0, w, h), img.CGImage);
 
    CGImageRef imageMasked = CGBitmapContextCreateImage(context);
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    [img release];
 
    return [UIImage imageWithCGImage:imageMasked];
    }
 
    @end

Bookmark and Share
Categories: iPhone SDK Tags: , , ,

Flash Builder 4 Network Monitor

September 1st, 2009 No comments

Flash Builder 4: Network Monitor and new debugger options from Mihai Corlan on Vimeo.


Bookmark and Share
Categories: Uncategorized Tags:

Objective C – HTTP POSTor GET Data

August 14th, 2009 3 comments

ASIHTTPRequest is an easy to use wrapper around the CFNetwork API that makes some of the more tedious aspects of communicating with web servers easier. It is written in Objective-C and works in both Mac OS X and iPhone applications.

It is suitable performing basic HTTP requests and interacting with REST-based services (GET / POST / PUT / DELETE). The included ASIFormDataRequest subclass makes it easy to submit POST data and files using multipart/form-data.

Here is an sample code on how easy is to make a http-post from objective c.

(Source: http://allseeing-i.com/ASIHTTPRequest/How-to-use)

ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];

[request setPostValue:@"Ben" forKey:@"first_name"];

[request setPostValue:@"Copsey" forKey:@"last_name"];

[request setFile:@"/Users/ben/Desktop/ben.jpg" forKey:@"photo"];

How to install and use ASIHTTPRequest in an iPhone project ?

1) Add the files

Copy the files you need to your project folder, and add them to your Xcode project. An overview of the ASIHTTPRequest source files appears here.

2) Link against CFNetwork, SystemConfiguration and zlib

Choose Project -> Edit Active Target from the menu.

Click the plus button in the bottom left of the window.

Choose “CFNetwork.framework” from the list, and click Add.

Repeat the same operation for “SystemConfiguration.framework” and “libz.1.2.3.dylib”

Bookmark and Share
Categories: iPhone SDK Tags: , , ,

Objective C: Read iPhone Preferences From Application

July 19th, 2009 No comments

You can read preferences from your iPhone Application using the NSUserDefaults class from iPhone SDK.

Here is how you can read the delay value before the phone is starting to dial a number

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
delayBeforeDialing = [userDefaults floatForKey:@"delayBeforeDialing"];

The key, “delayBeforeDialing” in this example, needs to match the Key value in Root.plist.

There are different accessor methods depending on the type of variable you want to retrieve.

* arrayForKey
* boolForKey
* dataForKey
* dictionaryForKey
* floatForKey
* integerForKey
* objectForKey
* stringArrayForKey
* stringForKey

You don’t have to use a UI for your preferences. If you just want to conveniently store values associated with your application, that you can read back later, you can use the setter methods of NSUserDefaults.

Bookmark and Share

Objective C: Show online image on iPhone

July 18th, 2009 No comments

By default the UIImageView control from the iPhone sdk does not allow us to load images from a specific url. In this case we do a little tryck and use a UIWebView.

- (void)loadImage:(NSString*)url frame:(CGRect)frame {
NSString* textHTML = @"
<!--
body {
background-color: transparent;
color: white;
}
-->
<img src="\" alt="" width="%0.0f" height="%0.0f" />
";
 
NSString* html = [NSString stringWithFormat:textHTML, url, frame.size.width, frame.size.height];
 
if(webView == nil) {
webView = [[UIWebView alloc] initWithFrame:frame];
[self.view addSubview:webView];
}
 
[webView loadHTMLString:html baseURL:nil];
}

Bookmark and Share

Flex Array Performance: For vs. ForEach

July 13th, 2009 No comments

We made a little test to see the flex performance on parsing an large array.

Here is the experiment:

var size:Number = 10000000;
var arr:Array = [];
for (var i:int=0; i
var time:Number, o:Object;
 
// for()
time = getTimer();
for (i=0; i=0; i--) { arr[i]; }
trace("for reversed test: "+(getTimer()-time)+"ms");
 
// for..in
time = getTimer();
for each(o in arr) { o; }
trace("for each test: "+(getTimer()-time)+"ms");

And here are the results:

for test: 124ms
for reversed test: 110ms
for each test: 261ms

We wish you to use this results wisely !

————————
The TiMeister Team

Bookmark and Share

Flex: Unable To Open locale en_US or fr_FR

July 13th, 2009 2 comments

If you want to create a localized application you may find yourself in a strange situation when you did all the steps like in the book, but you continue to receive the “Unable to open locale xx_XX” error messages.

To simulate a fix on this issue we will take the example of adding French to your app.

Basic steps:
- The first step is to create a fr_FR folder under the /locale/ one exactly like in the Flex documentation and then add the translated bundle.properties file.
- The second step is to add the compiler options: -locale en_US,fr_FR

Extra steps you need to make in order to get rid of the ugly “unable to open locale” error message:

1. goto the following path :

<flex-install-folder>/sdks/<current-sdk-folder>/bin/

for windows it’s: C:\Program Files\Adobe\Flex Builder 3\sdks\3.2.0\bin\

2. Execute the following command:

> copylocale.exe en_US fr_FR

That’s all, hope we helped you!
————————-

The TiMeister Team

Bookmark and Share

FLEX: Why is stage == null?

July 13th, 2009 1 comment

Hello,

If you are trying to access the stage of your application right when your app is completed then you’re doing something wrong.

BAD CODE Most of the cases programmers make the following mistake:

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init()">
    <mx:Script>
        <![CDATA[
            import flash.display.StageDisplayState;
            private function init():void
            {
                var s:Stage = this.stage; //<<-- this.stage == null...why??
                s.scaleMode = StageScaleMode.EXACT_FIT;
            }
        ]]>
    </mx:Script>
</mx:WindowedApplication>

GOOD CODE : The correct approach is the following:

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication
       xmlns:mx="http://www.adobe.com/2006/mxml"
       creationComplete="init()">
    <mx:Script>
        <![CDATA[
            import flash.display.StageDisplayState;
            private function init():void
            {
                this.systemManager.stage.scaleMode = StageScaleMode.EXACT_FIT;
            }
        ]]>
    </mx:Script>
</mx:WindowedApplication>

Hope we helped you with this issue we also had in our beginning as Flex Devlopers

Bookmark and Share

Top Flex Blogs and Resources

July 5th, 2009 No comments

Hello,

We would like to share with the list with our preferred blogs on adobe flex news , and also the top flex resource websites that could came handy anytime

NEWS and Cool Stuff:

* Mihai Corlan’s personal blog
http://corlan.org – Mihai is a flash platform evangelist at Adobe Inc. and one of the most interesting peoples we meet

* Doug McCune
http://dougmccune.com/blog/ – Doug is a pretty big name in the Flex community (he gives presentations all over the country at Flex events), most of the items you are going to find on his site are examples of cool applications built using Flex.

* CFLEX: Community Flex

http://www.cflex.net/

* Dzone
http://www.dzone.com/links/index.html – Dzone is a great community based site for sharing developer links. The site is setup in a similar fashion as popular sites such as Digg or Reddit.

* Flex.org
http://flex.org/ – Flex.org is the main community site for Flex developers, which includes a showcase and resources for everything from PHP to .Net.

Resources & Examples:

* Adobe Flex Developer Center
http://www.adobe.com/devnet/flex/ – The Adobe Developer Center is great resource for complete tutorials and articles on how to get started with Flex or any of the other Adobe products. The other Adobe resource is the Cookbook which is built off of community code snippets that solve small programming tasks.

* Flex Examples
Peter deHaan currently works for Adobe on the Flex SDK QA team. He writes so many small tutorials that it’s hard to even keep up with this man on any level.

* Alex Harui
http://blogs.adobe.com/aharui/ -Alex writes short posts that are usually nice Flex examples solving common and uncommon problems people run across in Flex. He works with the Adobe Flex core team in San Francisco.

* ScaleNine
http://www.scalenine.com/ – Skins and Themes for Flex and AIR

* Flex SDK

http://opensource.adobe.com/wiki/display/flexsdk/Flex+SDK

* Flex Showcase

http://flex.org/showcase/

* Flex Developer Center

http://www.adobe.com/devnet/flex/

* Franto.com
http://www.franto.com/ – Flex, AIR, Flash, ActionScript Tutorials, Tips, Tricks.

* The Flex Show

http://www.theflexshow.com/blog/

* Marco Casario

http://casario.blogs.com/mmworld/

Bookmark and Share