[objective-c]UIImageの作り方

UIImageの作り方

NSString*fn=@"image.png";
UIImage*image1=[UIImage imageNamed:fn];
UIImage*image2=[UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@",[[NSBundle mainBundle] bundlePath],fn]];

NSURL*url=[NSURL URLWithString:@"http://yourdomain/image.png"];
NSData*data=[NSData dataWithContentsOfURL:url];
UIImage*image3=[UIImage imageWithData:data];

参考サイト
UIImage Class Reference
http://developer.apple.com/library/ios/#documentation/uikit/reference/UIImage_Class/Reference/Reference.html

[objective-c]animateWithDuration

beginAnimationsはiOS4以降非推奨なので、
より便利なanimateWithDurationを使いましょう。

[UIView animateWithDuration:0.3
    animations:^{
        //アニメーション内容
        targetView.frame=CGRectMake(0, 0, 100, 100);
    }
    completion:^(BOOL finished){
        //アニメーションが終わったとき
        [targetView removeFromSuperview];
        [targetView release];
        targetView=nil;
    }
];

参考サイト
UIView ClassMethods
http://developer.apple.com/library/ios/#documentation/uikit/reference/uiview_class/UIView/UIView.html#//apple_ref/doc/uid/TP40006816-CH3-SW110

[iOS6]UICollectionView

iOS6から使えるUICollectionViewを試しました。
UICollectionViewはこういうやつです。
sc00

サンプルプロジェクトファイル(SampleCollectionView.zip)
sc01

ファイルはこんな感じにする。
スクリーンショット 2013-02-08 15.46.32

RootViewController.h

#import <UIKit/UIKit.h>
#import "CollectionCell.h"
#import "CollectionHeaderView.h"

@interface RootViewController : UIViewController{
    
@private
    NSMutableArray*photos;
    int cellcnt;
}
@property (retain, nonatomic) IBOutlet UICollectionView *collectionView;

@end

RootViewController.m 追記部分

-(NSString*)pzero:(NSString*)s keta:(int)keta{
    if (s.length>=keta) {
        return s;
    }
    do {
        s=[NSString stringWithFormat:@"0%@",s];
    } while (s.length<keta);
    return s;
}
-(NSString*)pzeroByInt:(int)n keta:(int)keta{
    NSString*s=[NSString stringWithFormat:@"%d",n];
    if (s.length>=keta) {
        return s;
    }
    do {
        s=[NSString stringWithFormat:@"0%@",s];
    } while (s.length<keta);
    return s;
}
-(float)getFillRatio:(CGSize)sourceSize targetSize:(CGSize)targetSize{
    CGFloat widthRatio  = targetSize.width  / sourceSize.width;
    CGFloat heightRatio = targetSize.height / sourceSize.height;
    return (widthRatio > heightRatio) ? widthRatio : heightRatio;
}
-(UIImage*)getResizeImageFillCrop:(UIImage*)img size:(CGSize)_size{
    CGFloat ratio=[self getFillRatio:img.size targetSize:_size];
    CGSize resizedSize = CGSizeMake(roundf(img.size.width*ratio), roundf(img.size.height*ratio));
    
    UIGraphicsBeginImageContext(resizedSize);
    [img drawInRect:CGRectMake(0, 0, resizedSize.width, resizedSize.height)];
    UIImage* resizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return [self getCropImage:resizedImage rect:CGRectMake((resizedImage.size.width-_size.width)*0.5, (resizedImage.size.height-_size.height)*0.5, _size.width, _size.height)];
}
-(UIImage*)getCropImage:(UIImage*)img rect:(CGRect)rect{
    CGImageRef imgref=CGImageCreateWithImageInRect([img CGImage],rect);
    UIImage *result=[UIImage imageWithCGImage:imgref];
    CGImageRelease(imgref);
    return result;
}



-(void)initCollection{
    photos=[[NSMutableArray alloc]initWithCapacity:11];
    int i;
    for (i=0; i<23; i++) {
        UIImage*img=[UIImage imageNamed:[NSString stringWithFormat:@"sc%@.png",[self pzeroByInt:i keta:2]]];
        [photos addObject:[self getResizeImageFillCrop:img size:CGSizeMake(78, 78)]];
        //[photos addObject:img];
    }
    cellcnt=[photos count];
    [self.collectionView registerClass:[CollectionCell class] forCellWithReuseIdentifier:@"MY_CELL"];
    UINib *headerNib = [UINib nibWithNibName:@"CollectionHeaderView" bundle:nil];
    [self.collectionView registerNib:headerNib forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"MY_HEADER"];
}
-(void)resetCollection{
    [self.collectionView reloadData];
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [photos count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MY_CELL" forIndexPath:indexPath];
    cell.imageview.image=[photos objectAtIndex:indexPath.item];
    return cell;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    CollectionHeaderView *headerView=[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"MY_HEADER" forIndexPath:indexPath];
    headerView.label.text=@"セクションヘッダー";
    return headerView;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeMake(200, 50);
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    UIImage *image = [photos objectAtIndex:indexPath.item];
    return CGSizeMake(image.size.width, image.size.height);
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initCollection];
}

RootViewController.xib
スクリーンショット 2013-02-08 15.53.24

CollectionCell.h

#import <UIKit/UIKit.h>

@interface CollectionCell : UICollectionViewCell{
    UIImageView*imageview;
}
@property(nonatomic,assign)UIImageView*imageview;
@end

CollectionCell.m

#import "CollectionCell.h"

@implementation CollectionCell
@synthesize imageview;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor=[UIColor whiteColor];
        UIImageView *iv=[[UIImageView alloc] initWithFrame:CGRectMake(2, 2, frame.size.width - 4, frame.size.height - 4)];
        iv.autoresizingMask=18;
        [self.contentView addSubview:iv];
        self.imageview=iv;
    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

- (void)setSelected:(BOOL)selected{
    [super setSelected:selected];
    if(selected){
        self.backgroundColor=[UIColor cyanColor];
    }else{
        self.backgroundColor=[UIColor whiteColor];
    }
}

@end

CollectionHeaderView.h

#import <UIKit/UIKit.h>

@interface CollectionHeaderView : UICollectionReusableView

@property (nonatomic,assign) IBOutlet UILabel *label;

@end

CollectionHeaderView.m

#import "CollectionHeaderView.h"

@implementation CollectionHeaderView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end

CollectionHeaderView.xib
スクリーンショット 2013-02-08 15.56.41

便利ですね

[iOS6]UIActivity

iOS6から使えるUIActivityを試しました。
UIActivityはこういうやつです。
sc00

-(void)startActivity:(int)type{
    NSString*text=@"Hello World!! ";
    NSArray*actItems=nil;
    UIImage*image=nil;
    NSURL*url=nil;
    UIActivityViewController*actView;
    
    switch (type) {
        case 0://text
            actItems=[NSArray arrayWithObjects:text, nil];
            break;
        case 1://text + image
            image=_img0.image;
            actItems=[NSArray arrayWithObjects:text,image, nil];
            break;
        case 2://text + url
            url=[NSURL URLWithString:_tf0.text];
            actItems=[NSArray arrayWithObjects:text,url, nil];
            break;
            
        default:
            break;
    }
    
    
    actView=[[[UIActivityViewController alloc] initWithActivityItems:actItems applicationActivities:nil] autorelease];
    
    actView.completionHandler = ^(NSString *activityType, BOOL completed){
        //投稿した時
        NSLog(@" activityType: %@", activityType);
        NSLog(@" completed: %i", completed);
        if (!completed) {//キャンセル or 失敗
            
        }
    };
    
    [self presentViewController:actView animated:YES completion:^{
        //出現アニメ終了時
        NSLog(@"appear!!");
    }];
}

//実行
[self startActivity:1];

上記startActivityメソッドで
type:0
sc00

type:1
sc01

type:2
sc02

type:1でTwitterをタップしたところ
sc04

[iOS6]Safariでinput type="file"

iOS6のSafariからformのinput type=”file”に対応しているので試しました。
codeSample

sc00
formを作ると左のように表示される。

sc01
[ファイルを選択]をタップしたところ

sc02
[既存の項目を選択]から画像を選択したところ

sc03
[既存の項目を選択]から動画を選択すると、「ビデオを圧縮中…」と出る

sc04
動画のサムネイルが表示される

sc05
[送信]をタップして遷移したところ

index.html

<!DOCTYPE html>
<html lang="ja">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="Content-Script-Type" content="text/javascript">
<meta http-equiv="Content-Style-Type" content="text/css">
<title>sample00</title>
<meta name="description" content="****">
<meta name="keywords" content="****">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta name="format-detection" content="telephone=no,address=no,email=no">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<form method="post" action="upload.php" enctype="multipart/form-data">
	<input type="file" name="selectedFile" />
	<br/>
	<br/>
	<input type="submit"/>
</form>
</body>
</html>

upload.php

<!DOCTYPE html>
<html lang="ja">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="Content-Script-Type" content="text/javascript">
<meta http-equiv="Content-Style-Type" content="text/css">
<title>sample00</title>
<meta name="description" content="****">
<meta name="keywords" content="****">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta name="format-detection" content="telephone=no,address=no,email=no">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<?php
$ext=end(explode('.', $_FILES["selectedFile"]["name"]));
$filename='./test.'.$ext;
$result = @move_uploaded_file( $_FILES["selectedFile"]["tmp_name"], $filename);
if($result){
	echo '<img src="'.$filename.'"/><br/>';

	foreach($_FILES["selectedFile"] as $key => $v){
		echo $key.' : '.$v.'<br/>';
	}
}else{
	echo 'エラー';
}
?>
</body>
</html>

[objective-c]ELCImagePickerControllerを使ってカメラロールの写真を複数選択

ELCImagePickerControllerを使ってカメラロールの写真を複数選択

1) LibraryをLinkさせる
・プロジェクトを選択
・TARGETSを選択
・Build Phasesをクリック
・Link Binary With Librariesをクリック
・「+」をクリック
・AssetsLibrary.frameworkを選択して「add」
スクリーンショット

2)ヘッダファイルでimport

#import "ELCImagePickerController.h"
#import "ELCAlbumPickerController.h"

3)実装

-(float)getFillRatio:(CGSize)sourceSize targetSize:(CGSize)targetSize{
    CGFloat widthRatio  = targetSize.width  / sourceSize.width;
    CGFloat heightRatio = targetSize.height / sourceSize.height;
    return (widthRatio > heightRatio) ? widthRatio : heightRatio;
}
-(UIImage*)getResizeImageFill:(UIImage*)img size:(CGSize)_size{
    CGFloat ratio=[self getFillRatio:img.size targetSize:_size];
    CGSize resizedSize = CGSizeMake(roundf(img.size.width*ratio), roundf(img.size.height*ratio));
    
    UIGraphicsBeginImageContext(resizedSize);
    [img drawInRect:CGRectMake(0, 0, resizedSize.width, resizedSize.height)];
    UIImage* resizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return resizedImage;
}




-(void)startPhotoSelect{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        ELCAlbumPickerController *albumController = [[[ELCAlbumPickerController alloc] initWithNibName:@"ELCAlbumPickerController" bundle:[NSBundle mainBundle]]autorelease];
        ELCImagePickerController *elcPicker = [[[ELCImagePickerController alloc] initWithRootViewController:albumController]autorelease];
        [albumController setParent:elcPicker];
        [elcPicker setDelegate:self];
        [self presentModalViewController:elcPicker animated:YES];
    } else {
    }
}
- (void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info {
	[self dismissModalViewControllerAnimated:YES];
    if ([info count]<1) {
        return;
    }
    int i;
    NSMutableDictionary*d;
    CGSize imageSize=CGSizeMake(100, 100);
    for (i=0; i<[info count]; i++) {
        d=[info objectAtIndex:i];
        UIImageView *imageview;
        imageview=[[UIImageView alloc] initWithImage:[self getResizeImageFill:[d objectForKey:UIImagePickerControllerOriginalImage] size:imageSize]];
        [self.view addSubview:imageview];
        imageview.frame=CGRectMake(20.0*i, 20.0*i, imageSize.width, imageSize.height);
    }
}
- (void)elcImagePickerControllerDidCancel:(ELCImagePickerController *)picker {
	[self dismissModalViewControllerAnimated:YES];
}

//ここから実行
-(IBAction)whenTapBtn:(id)sender{
    [self startPhotoSelect];
}

github:ELCImagePickerController
https://github.com/elc/ELCImagePickerController

[objective-c]GCDを使った非同期処理

GCDを使った非同期処理
GCD:Grand Central Dispatch

dispatch_queue_t main=dispatch_get_main_queue();
dispatch_queue_t sub=dispatch_queue_create("net.ktyr.sample", NULL);
dispatch_async(sub, ^{
    //何か重たい処理
    UIImage*image=[UIImage imageNamed:@"thankyou.png"];
    dispatch_async(main, ^{
        //重たい処理が終わったとき
        [myImageView setImage:image];
    });
});
dispatch_release(sub);

[iPhone Apps]PhotoTile

iPhoneアプリ「フォトタイル」をリリースしました。

フォトタイルは複数の写真をササッとつなげて一枚にするアプリです。
写真を複数枚アップロードしたい!そんなときこれでササッとつないで投稿できます。
Twitter,Facebookに対応しており、作った写真をすぐにアップロードすることができます。
つなぎ方、角円などを調整して自分好みの設定で写真をつなぎましょう。

主な機能
■複数の写真をつなぐことができます。
■つなぎ方を選択できます。
・縦一列
・横一列
・格子状
・サイズ位置ランダム配置
■つないだ後に写真の順番を入れ替えられます。
■つないだ後に不要な写真を削除できます。
■縦横サイズを調整できます。
■縁の太さを調整できます。
■角円を調整できます。
■背景色を調整できます。
■写真をTwitterへアップロードできます。
■写真をFacebookへアップロードできます。
■写真を使用中のiPhone,iPodへ保存できます。

PhotoTile is an app that can combine multiple photos into single photo.
when you want to upload multiple photos, You can do it quickly with this app.
You can upload photos to Twitter,Facebook.

Features
■Enable to combine multiple photos.
■Enable to select combine method.
・vertical
・horizontal
・grid
・random position, random size
■Enable to change the order of the photos.
■Enable to delete unwanted photos.
■Enable to adjust vertical,horizontal size.
■Enable to adjust border thickness.
■Enable to adjust corner radius.
■Enable to adjust background color.
■Enable to upload photo to Twitter.
■Enable to upload photo to Facebook.
■Enable to save photo to your device.

フォトタイル
フォトタイル

PhotoTile(English)

フォトタイルフォトタイル

フォトタイルフォトタイル

フォトタイル

[objective-c]RGBAで指定した色のUIImageを生成

RGBAで指定した色のUIImageを生成

-(UIImage*)get255ColorRectImage:(float)r g:(float)g b:(float)b alpha:(float)alpha size:(CGSize)_size{
    UIGraphicsBeginImageContext(_size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBFillColor(context, r/255.0,g/255.0,b/255.0,alpha/255.0);
    CGContextFillRect(context, CGRectMake(0.0,0.0,_size.width,_size.height));
    UIImage *screenImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return screenImage;
}

UIImage*redImage=[self get255ColorRectImage:255.0 g:0.0 b:0.0 alpha:255.0 size:CGSizeMake(100, 100)];