2011年6月26日 星期日

Detect the version of app

NSString* version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];

2011年6月19日 星期日

get rgb data from UIImage

xxx.h

typedef unsigned char byte;

typedef struct RGBPixel    
{
    byte    red;
    byte    green;
    byte    blue;
}   RGBPixel;

typedef struct RGBAPixel    
{
    byte    red;
    byte    green;
    byte    blue;
    byte    alpha;    
}   RGBAPixel;

@interface UIImage(XXX)
- (RGBPixel*)bitmapFromBMP;
- (RGBAPixel*)bitmapFromPNG;
@end

xxx.m

#define RGBA                4
#define RGBA_8_BIT          8

@implementation UIImage(XXX)

- (RGBPixel*)bitmapFromBMP
{
    CFDataRef bitmapData = CGDataProviderCopyData(CGImageGetDataProvider(self.CGImage)); 
    UInt8* pixelByteData = malloc(CFDataGetLength(bitmapData));
    if (!pixelByteData)
        return nil;
    
    CFDataGetBytes(bitmapData, CFRangeMake(0, CFDataGetLength(bitmapData)), pixelByteData);
    return (RGBPixel*)pixelByteData;
}

- (RGBAPixel*)bitmapFromPNG
{
    size_t bytesPerRow = self.size.width * RGBA;
    size_t byteCount = bytesPerRow * self.size.height;
    CGContextRef context = 0;
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    UInt8* pixelByteData = malloc(byteCount);
    RGBAPixel* pixelData = nil;
    
    if (!colorSpace) 
    {
        return nil;
    }
    
    if (!pixelByteData)  
    {
        CGColorSpaceRelease( colorSpace );
        return nil;
    }
    context = CGBitmapContextCreate((void*) pixelByteData,
                                    self.size.width,
                                    self.size.height,
                                    RGBA_8_BIT,
                                    bytesPerRow,
                                    colorSpace,
                                    kCGImageAlphaPremultipliedLast);
    
    if (!context)
    {
        free( pixelByteData );
        CGColorSpaceRelease( colorSpace );
        return nil;
    }
    CGRect rect = { { 0 , 0 }, { self.size.width, self.size.height }    };    
    CGContextDrawImage( context, rect, self.CGImage );
    pixelData = (RGBAPixel*) CGBitmapContextGetData(context);
    
    return pixelData;
    
}

@end

在 iPhone 上實現小畫家基本功能

.h

UIImageView *drawImage_;
CGPoint lastPoint_;

.m
-(id) init
{
if( (self=[super init])) {
        drawImage_ = [[[UIImageView alloc]initWithImage:nil]autorelease];
        drawImage_.frame = CGRectMake(0, 50, 320,400);
        [[[CCDirector sharedDirector]openGLView] addSubview:drawImage_];
        self.isTouchEnabled = YES;
}
return self;
}

- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    lastPoint_ = [touch locationInView:drawImage_];    
}

- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint currentPoint = [touch locationInView:drawImage_];
    UIGraphicsBeginImageContext(drawImage_.frame.size);
    
    [drawImage_.image drawInRect:CGRectMake(0, 0, drawImage_.frame.size.width, drawImage_.frame.size.height)];
    CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound); 
    CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);
    CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0,0.0,0.0, 1.0);
    CGContextBeginPath(UIGraphicsGetCurrentContext());
    CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint_.x, lastPoint_.y);
    CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
    CGContextStrokePath(UIGraphicsGetCurrentContext());
    drawImage_.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    lastPoint_ = currentPoint;
}




2011年6月17日 星期五

Detect the orientation of iPhone view

step 1: add a notification

    [[NSNotificationCenter defaultCenter] addObserver:self 
                         selector:@selector(receivedRotate:)                                          
                             name:UIDeviceOrientationDidChangeNotification 
                           object:nil];



step 2: remove a notification

    [[NSNotificationCenter defaultCenter] removeObserver:self  
                             name:UIDeviceOrientationDidChangeNotification 
                           object:nil];


step 3: implement "receiveRotate"

- (void)receivedRotate:(NSNotification*)notification
{
    UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;
    if (deviceOrientation == UIDeviceOrientationPortrait)
    {
        ...
    }
}

Transition between portrait and landscape

Portrait View :
WhatsOnLandscapeController *whatsOnLandscape = [[[WhatsOnLandscapeController alloc] initWithNibName:@"WhatsOnLandscape" bundle:nil]autorelease];

[whatsOnLandscape setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
[self presentModalViewController:whatsOnLandscape animated:YES];

Landscape View :
[Leave Landscape View]
[self dismissModalViewControllerAnimated:YES];

2011年6月15日 星期三

List iPhone Country Code

NSLocale *currentLocale = [NSLocale currentLocale];

NSArray *countryArray = [NSLocale ISOCountryCodes];

for (NSString *key in countryArray)
{
NSLog(@"code : %@\n",key);
NSString *displayNameString = [currentLocale displayNameForKey:NSLocaleCountryCode value:key];
NSLog(@"displayNameString : %@\n",displayNameString);
}


NSLog(@"Country Code is %@", [currentLocale objectForKey:NSLocaleCountryCode]);

To shutdown multitasking for app

If you do not want your application to remain in the background when it is quit, you can explicitly opt out of the background execution model by adding the UIApplicationExitsOnSuspend key to your application’s Info.plist file and setting its value to YES

2011年6月13日 星期一

Xcode4 Build Error - "couldn't add 'com.apple.XcodeGenerated' ta"

warning: couldn't add 'com.apple.XcodeGenerated' tag to '/Users/ErawppaArtist/Library/Developer/Xcode/DerivedData/Gem-fazbkuxrbdcggzdfnxewcqymqaey/Build/Intermediates/Gem.build': Error Domain=NSPOSIXErrorDomain Code=2 UserInfo=0x20212f0a0 "The operation couldn’t be completed. No such file or directory"

Solution
sudo chmod -R 777 /Users/XXX/Library/Developer/

2011年6月10日 星期五

Customize NavigationBarItem

    UIViewController *mine = [self.navigationController.viewControllers objectAtIndex:0];
    
    UIImage *nextImg = [UIImage imageNamed:@"NextIcon.png"];
    UIButton *nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [nextBtn setBackgroundImage:nextImg forState:UIControlStateNormal];
    nextBtn.frame = CGRectMake(0, 0, nextImg.size.width, nextImg.size.height);
    [nextBtn addTarget:self action:@selector(nextAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *next = [[[UIBarButtonItem alloc] initWithCustomView:nextBtn]autorelease];
    
    mine.navigationItem.rightBarButtonItem = next;

利用 NSDate 抓取今日時間

- (NSString *)todayDate
{
    NSDate *today = [NSDate date];    
    NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]autorelease];
    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
    NSDateComponents *components = [gregorian components:unitFlags fromDate:today];
    return [NSString stringWithFormat:@"%.4d-%.2d-%.2d",[components year],[components month],[components day]];
}

- (NSString *)currTime
{
    NSDate *today = [NSDate date];    
    NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]autorelease];
    NSUInteger unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit
    NSDateComponents *components = [gregorian components:unitFlags fromDate:today];
    return [NSString stringWithFormat:@"%.2d:%.2d",[components hour],[components minute]];
}

2011年6月1日 星期三

iPhone + Base64

Download Base64 and add it into your project.

#import "NSData+Base64.h"


{
    NSString *str =@"tix.lo";
    
    NSData *strData = [str dataUsingEncoding:NSUTF8StringEncoding];
    
    NSString *encodedStr = [strData base64EncodedString];
    
    NSLog(@"Base64 Encoded: %@",encodedStr);
    
    //Base64 Decoding
    NSData *decodedData = [NSData dataFromBase64String:encodedStr];
    
    NSString *decodedStr = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
    
    NSLog(@"Base64 Decoded: %@",decodedStr );

}

source from : reference