2013年2月9日 星期六

NSNotificationCenter通知中心(用於一對多的通知)

//發送端:
 [NSNotificationCenter.defaultCenter postNotificationName:@"playIntro" object:self];

//接收端:
 [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(playIntro) name:@"playIntro" object:self.moviePlayer];

 //接收後註銷:
 [NSNotificationCenter.defaultCenter removeObserver:self name:@"playIntro" object:self.moviePlayer];

2013年2月4日 星期一

Iterative與Recursive的差異


迭代法以確定的部分作為起始點,循序漸進推演,最後求得答案。

遞迴法找出一套縮小問題範疇的規律,以此規律不斷縮小問題,直到能釐清細節,找到確定的部份。

迭代法與遞迴法恰好顛倒:迭代法是針對已知,逐步累積,直至周全;遞迴法是針對未知,反覆拆解,直至精細。

截自http://www.csie.ntnu.edu.tw/~u91029/IterativeRecursive.html

開場影片

//最好調整成放在AppDelegate中,因為View不會那麼早被初始化

header, #import <MediaPlayer/MediaPlayer.h>
@interface RootViewController ()
{  
}
@property (nonatomic, strong) MPMoviePlayerController *moviePlayer;
@end
 
@implementation RootViewController
@synthesize moviePlayer;
 
-(void)playIntro{
    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:@"appIntro" ofType:@"mp4"]];
    self.moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:url];
    //註冊通知中心,當影片播放完畢,進行回呼方法(playbackStateDidFinish)
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(playbackStateDidFinish)
                                                 name:MPMoviePlayerPlaybackDidFinishNotification
                                               object:self.moviePlayer ];
    //播放器參數設定
    self.moviePlayer.controlStyle = MPMovieControlStyleNone;
    self.moviePlayer.scalingMode = MPMovieScalingModeAspectFill;
    self.moviePlayer.repeatMode = MPMovieRepeatModeNone;
    self.moviePlayer.view.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin|UIViewAutoresizingFlexibleLeftMargin
   |UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleTopMargin;
    //設定播放器大小
    [self.moviePlayer.view setFrame:self.view.bounds];
    [self.view addSubview:self.moviePlayer.view];
    //播放
    [self.moviePlayer play];
}
 
- (void)playbackStateDidFinish{
    //註銷通知中心
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:MPMoviePlayerPlaybackDidFinishNotification
                                                  object:self.moviePlayer];
    //停止播放
    [self.moviePlayer stop];
    //移除播放器
    [self.moviePlayer.view removeFromSuperview];
}

UIWebView截取html

//載取html改變頁面寬度後塞回
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
//修改頁面meta值
NSString *meta = [NSString stringWithFormat:@"document.getElementsByName(\"viewport\")[0].content = \"width=%f, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no\"", webView.frame.size.width];
[webView stringByEvaluatingJavaScriptFromString:meta];
}

//增加UTF-8編碼
     [webView stringByEvaluatingJavaScriptFromString:  @"var tagHead =document.documentElement.firstChild;" 
    "var tagMeta = document.createElement(\"meta\");"
    "tagMeta.setAttribute(\"http-equiv\", \"Content-Type\");"   "tagMeta.setAttribute(\"content\", \"text/html; charset=utf-8\");"
    "var tagHeadAdd = tagHead.appendChild(tagMeta);"]; 
//截取網頁圖片,修改圖片大小
[webView stringByEvaluatingJavaScriptFromString:
@"var script = document.createElement('script');"
"script.type = 'text/javascript';"
"script.text = \"function ResizeImages() { "
"var myimg,oldwidth;"
"var maxwidth=380;" //頁面寬度
"for(i=0;i <document.images.length;i++){"
"myimg = document.images[i];"
"if(myimg.width > maxwidth){"
"oldwidth = myimg.width;"
"myimg.width = maxwidth;"
"myimg.height = myimg.height * (maxwidth/oldwidth);"
"}"
"}"
"}\";"
"document.getElementsByTagName('head')[0].appendChild(script);"];
 
[webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];  

2013年2月3日 星期日

旋轉手勢辨識


#import <UIKit/UIKit.h>

@interface MyImageView : UIImageView{
    CGPoint startPoint;
    CGAffineTransform currentTransform;
}

@end


#import "MyImageView.h"
#import <QuartzCore/QuartzCore.h>
@implementation MyImageView

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

-(id)initWithCoder:(NSCoder* )aDecoder{
    self = [super initWithCoder:aDecoder];
    if (self) {
        //啟動觸控
        self.userInteractionEnabled= YES;
        //設定圖檔
        self.image = [UIImage imageNamed:@"image4.jpg"];
        //加入手勢
        
        /*
        UIPanGestureRecognizer* pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(doMove:)];
        [self addGestureRecognizer:pan];
        */
        /*
        UISwipeGestureRecognizer* swipe1 = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(doLeft:)];
        swipe1.direction = UISwipeGestureRecognizerDirectionLeft;
        //要求雙擊
        swipe1.numberOfTouchesRequired = 2;
        [self addGestureRecognizer:swipe1];
        
        UISwipeGestureRecognizer* swipe2 = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(doRight:)];
        //要求雙擊
        swipe2.numberOfTouchesRequired = 2;
        swipe2.direction = UISwipeGestureRecognizerDirectionRight;
        [self addGestureRecognizer:swipe2];
        */
        
        UIRotationGestureRecognizer* rotation= [[UIRotationGestureRecognizer alloc]initWithTarget:self action:@selector(doRotate:)];
        [self addGestureRecognizer:rotation];
        
    }
    return self;
}

-(void)doRotate:(UIRotationGestureRecognizer*)recognizer{
    //recognizer中取得並旅轉
    self.layer.affineTransform = CGAffineTransformRotate(currentTransform, recognizer.rotation);
}

-(void)doLeft:(UISwipeGestureRecognizer*)recognizer{
    CGPoint newPoint = CGPointMake(self.center.x-50, self.center.y);
    self.center = newPoint;
}
-(void)doRight:(UISwipeGestureRecognizer*)recognizer{
    CGPoint newPoint = CGPointMake(self.center.x+50, self.center.y);
    self.center = newPoint;
}
/*
-(void)doMove:(UIPanGestureRecognizer*)recognizer{
    //取得解控點
    CGPoint clickPoint = [recognizer translationInView:self];
    NSLog(@"Move的點是(%.1f,%.1f)",clickPoint.x,clickPoint.y);
    //開始移動
    CGPoint newPoint = CGPointMake(startPoint.x+clickPoint.x, startPoint.y+clickPoint.y);
    self.center = newPoint;
}
*/
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    //取得觸控點
    CGPoint clickPoint = [[touches anyObject]locationInView:self];
    NSLog(@"觸控點在(%.1f,%.1f)",clickPoint.x,clickPoint.y);
    startPoint = clickPoint;
    currentTransform=self.layer.affineTransform;
}



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

@end

滑動手勢辨識


#import <UIKit/UIKit.h>

@interface MyImageView : UIImageView{
    CGPoint startPoint;
}

@end

#import "MyImageView.h"

@implementation MyImageView

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

-(id)initWithCoder:(NSCoder* )aDecoder{
    self = [super initWithCoder:aDecoder];
    if (self) {
        //啟動觸控
        self.userInteractionEnabled= YES;
        //設定圖檔
        self.image = [UIImage imageNamed:@"image4.jpg"];
        //加入手勢
        
        /*
        UIPanGestureRecognizer* pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(doMove:)];
        [self addGestureRecognizer:pan];
        */
        UISwipeGestureRecognizer* swipe1 = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(doLeft:)];
        swipe1.direction = UISwipeGestureRecognizerDirectionLeft;
        //要求雙擊
        swipe1.numberOfTouchesRequired = 2;
        [self addGestureRecognizer:swipe1];
        
        UISwipeGestureRecognizer* swipe2 = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(doRight:)];
        //要求雙擊
        swipe2.numberOfTouchesRequired = 2;
        swipe2.direction = UISwipeGestureRecognizerDirectionRight;
        [self addGestureRecognizer:swipe2];
        
    }
    return self;
}

-(void)doLeft:(UISwipeGestureRecognizer*)recognizer{
    CGPoint newPoint = CGPointMake(self.center.x-50, self.center.y);
    self.center = newPoint;
}
-(void)doRight:(UISwipeGestureRecognizer*)recognizer{
    CGPoint newPoint = CGPointMake(self.center.x+50, self.center.y);
    self.center = newPoint;
}
/*
-(void)doMove:(UIPanGestureRecognizer*)recognizer{
    //取得解控點
    CGPoint clickPoint = [recognizer translationInView:self];
    NSLog(@"Move的點是(%.1f,%.1f)",clickPoint.x,clickPoint.y);
    //開始移動
    CGPoint newPoint = CGPointMake(startPoint.x+clickPoint.x, startPoint.y+clickPoint.y);
    self.center = newPoint;
}
*/
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    //取得觸控點
    CGPoint clickPoint = [[touches anyObject]locationInView:self];
    NSLog(@"觸控點在(%.1f,%.1f)",clickPoint.x,clickPoint.y);
    startPoint = clickPoint;
}



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

@end


位移手勢辨識


#import <UIKit/UIKit.h>

@interface MyImageView : UIImageView{
    CGPoint startPoint;
}

@end


#import "MyImageView.h"

@implementation MyImageView

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

-(id)initWithCoder:(NSCoder* )aDecoder{
    self = [super initWithCoder:aDecoder];
    if (self) {
        //啟動觸控
        self.userInteractionEnabled= YES;
        //設定圖檔
        self.image = [UIImage imageNamed:@"image4.jpg"];
        //加入手勢
        UIPanGestureRecognizer* pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(doMove:)];
        [self addGestureRecognizer:pan];
    }
    return self;
}

-(void)doMove:(UIPanGestureRecognizer*)recognizer{
    //取得解控點
    CGPoint clickPoint = [recognizer translationInView:self];
    NSLog(@"Move的點是(%.1f,%.1f)",clickPoint.x,clickPoint.y);
    //開始移動
    CGPoint newPoint = CGPointMake(startPoint.x+clickPoint.x, startPoint.y+clickPoint.y);
    self.center = newPoint;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    //取得觸控點
    CGPoint clickPoint = [[touches anyObject]locationInView:self];
    NSLog(@"觸控點在(%.1f,%.1f)",clickPoint.x,clickPoint.y);
    startPoint = clickPoint;
}



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

@end

基本觸控


#import <UIKit/UIKit.h>

@interface MyImageView : UIImageView{
    CGPoint startPoint;
}

@end


#import "MyImageView.h"

@implementation MyImageView

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

-(id)initWithCoder:(NSCoder* )aDecoder{
    self = [super initWithCoder:aDecoder];
    if (self) {
        //啟動觸控
        self.userInteractionEnabled= YES;
        //設定圖檔
        self.image = [UIImage imageNamed:@"image4.jpg"];
    }
    return self;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    //取得觸控點
    CGPoint clickPoint = [[touches anyObject]locationInView:self];
    NSLog(@"觸控點在(%.1f,%.1f)",clickPoint.x,clickPoint.y);
    startPoint = clickPoint;
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    CGPoint clickPoint = [[touches anyObject]locationInView:self];
    //計算偏移值
    float offsetX = clickPoint.x - startPoint.x;
    float offsetY = clickPoint.y - startPoint.y;
    //設定新值並更新
    CGPoint newPoint = CGPointMake(self.center.x+offsetX, self.center.y+offsetY);
    self.center = newPoint;
    
}

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

@end

圖層動畫



#import <UIKit/UIKit.h>

@interface ViewController : UIViewController{
    CALayer* layer1;
    CALayer* layer2;
    CALayer* layer3;
    //目前的轉置矩陣
    CATransform3D currentTransform;
}

@property (retain, nonatomic) IBOutlet UIView *bgLayer;
- (IBAction)onYellowUp:(id)sender;
- (IBAction)onGreenUp:(id)sender;
- (IBAction)onRotateY:(id)sender;
@end




#import "ViewController.h"
#import <QuartzCore/QuartzCore.h>
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
[self setupCALayer];
    // Do any additional setup after loading the view, typically from a nib.
}

-(void)setupCALayer{
    layer1 =[[CALayer layer]retain];
    layer1.bounds = CGRectMake(0, 0, 100, 100);
    layer1.position = CGPointMake(100, 100);
    layer1.borderColor = [UIColor redColor].CGColor;
    layer1.borderWidth = 10;
    layer1.backgroundColor = [UIColor yellowColor].CGColor;
    layer1.cornerRadius = 15;
    layer1.opacity = 0.8;
    [self.bgLayer.layer addSublayer:layer1];
    
    layer2 =[[CALayer layer]retain];
    layer2.bounds = CGRectMake(0, 0, 100, 100);
    layer2.position = CGPointMake(120, 120);
    layer2.borderColor = [UIColor blueColor].CGColor;
    layer2.borderWidth = 10;
    layer2.backgroundColor = [UIColor greenColor].CGColor;
    layer2.cornerRadius = 15;
    layer2.opacity = 0.8;
    [self.bgLayer.layer addSublayer:layer2];
    
    //增加z
    layer2.zPosition = -5;
    
    //模擬3D動畫
    CATransform3D identity = CATransform3DIdentity;
    identity.m34 = 1/-50;
    self.bgLayer.layer.sublayerTransform = identity;
    currentTransform = identity;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [_bgLayer release];
    [super dealloc];
}
- (IBAction)onYellowUp:(id)sender {
    layer1.zPosition = 0;
    layer2.zPosition = -5;
}

- (IBAction)onGreenUp:(id)sender {
    layer1.zPosition = -5;
    layer2.zPosition = 0;
}

- (IBAction)onRotateY:(id)sender {
    CABasicAnimation* rotate = [CABasicAnimation animationWithKeyPath:@"sublayerTransform"];
    
    CATransform3D newTransform = CATransform3DRotate(currentTransform, M_PI/6, 0, 1, 0);
    rotate.toValue = [NSValue valueWithCATransform3D:newTransform];
    rotate.duration = 2;
    rotate.fillMode = kCAFillModeBoth;
    rotate.removedOnCompletion = NO;
    [self.bgLayer.layer addAnimation:rotate forKey:nil];
    currentTransform = newTransform;
}
@end

CALayer


-(void)setupCALayer{
    UIImage* image1 = [UIImage imageNamed:@"image10.jpg"];
    CALayer* myLayer = [CALayer layer];
    myLayer.bounds = CGRectMake(0, 0, 200, 150);
    myLayer.position = CGPointMake(100, 75);
    myLayer.contents = (id)image1.CGImage;
    [self.view.layer addSublayer:myLayer];
    
    CAShapeLayer* shapeLayer = [CAShapeLayer layer];
    CGMutablePathRef pathRef = CGPathCreateMutable();
    CGPathAddRect(pathRef,nil, CGRectMake(0, 0, 200, 50));
    shapeLayer.bounds = CGRectMake(0, 0, 200, 50);
    shapeLayer.position = CGPointMake(100, 125);
    shapeLayer.path = pathRef;
    shapeLayer.fillColor = [UIColor redColor].CGColor;
    shapeLayer.opacity = 0.6;
    [myLayer addSublayer:shapeLayer];
    
    CATextLayer* textLayer = [CATextLayer layer];
    textLayer.string = @"hello";
    textLayer.font = [UIFont systemFontOfSize:8].fontName;
    textLayer.fontSize = 24;
    textLayer.foregroundColor = [UIColor blackColor].CGColor;
    textLayer.bounds = CGRectMake(0, 0, 200, 50);
    textLayer.position = CGPointMake(100, 25);
    [shapeLayer addSublayer:textlayer];
}


- (IBAction)onButtonClick:(id)sender {
    [CATransaction begin];
    [CATransaction setAnimationDuration:5.0];
    myLayer.position = CGPointMake(100, 275);
    shapeLayer.fillColor = [UIColor greenColor].CGColor;
    textLayer.fontSize=36;
    [CATransaction commit];
}



- (IBAction)onTransformClick:(id)sender {
    [CATransaction setAnimationDuration:3.0];
    myLayer.affineTransform = CGAffineTransformMakeRotation(M_PI/2);
    myLayer.affineTransform = CGAffineTransformScale(myLayer.affineTransform, 2.0, 1.5);
}


- (IBAction)shadow:(id)sender {
    myLayer.shadowOpacity = 1.0;
    myLayer.shadowOffset = CGSizeMake(10, 100);
    myLayer.shadowColor = [UIColor blueColor].CGColor;
    myLayer.shadowRadius = 15;
    //設定pathCALayer的矩形,效果一樣但會加速
    myLayer.shadowPath = [UIBezierPath bezierPathWithRect:myLayer.bounds].CGPath;
}

//真正的動畫是不會動到基本資料的

- (IBAction)onAnimDown:(id)sender {
    CABasicAnimation* anim = [CABasicAnimation animationWithKeyPath:@"position.y"];
    anim.toValue = @300; //anim.toValue = [NSNumber numberWithInt:300];
    anim.duration = 5;
    [myLayer addAnimation:anim forKey:@"downAnim"];
}

- (IBAction)onAnimUp:(id)sender {
    CABasicAnimation* anim = [CABasicAnimation animationWithKeyPath:@"position.y"];
    anim.toValue = @50;
    anim.duration = 5;
    [myLayer addAnimation:anim forKey:@"downUp"];
}
- (IBAction)onCancelDown:(id)sender {
    [myLayer removeAnimationForKey:@"downAnim"];
    [myLayer removeAllAnimations];
}

- (IBAction)onTwinkleClick:(id)sender {
    CABasicAnimation* anim = [CABasicAnimation animationWithKeyPath:@"opacity"];
    anim.toValue = @0.1;
    anim.repeatCount = 5;
    anim.autoreverses = YES;
    anim.duration = 1.5;
    [myLayer addAnimation:anim forKey:@"twinkle"];
}


- (IBAction)onFlyClick:(id)sender {
    CAKeyframeAnimation* anim = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    CGMutablePathRef pathRef = CGPathCreateMutable();
    CGPathMoveToPoint(pathRef, nil, 100, 75);
    
    CGPathAddQuadCurveToPoint(pathRef, nil, 600, -50, 300, 300);
    anim.path = pathRef;
    anim.duration = 8.0;
    //設定代理物件
    anim.delegate = self;
    [myLayer addAnimation:anim forKey:@"fly"];
    

}

-(void)animationDidStart:(CAAnimation *)anim{
    myLayer.shadowOpacity = 1;
    myLayer.shadowColor = [UIColor redColor].CGColor;
    myLayer.shadowOffset= CGSizeMake(10,10);
    
}
-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    myLayer.shadowOpacity = 0;
}