Just a Computer Graphics Studio & My Life

[iOS] 視圖坐標系轉換

想要把一個在視圖A上的子視圖的坐標系轉換到視圖B上(或相反)該怎麼做呢?一開始真不懂上一句話的意思,看來最近記憶力理解力衰退不少QQ簡單來講就是視圖坐標系轉換

[iOS] 視圖坐標系轉換1

這是在storyboard上的界面設定。

可以不用管下面那個Sad Button唷~黃色是view1,紅色是button1,就以這兩者來和view互動一下吧~

雖然已知有API可以呼叫,但是還是想實際看一下跑出來的結果~

有兩個方法:

  • – (CGRect)convertRect:(CGRect)rect toView:(UIView *)view;
  • – (CGRect)convertRect:(CGRect)rect fromView:(UIView *)view;

首先是toView:

    NSLog(@"Before: self.view:%@",self.view);
    NSLog(@"Before: self.view1:%@",self.view1);
    NSLog(@"Before: self.button1:%@",self.button1);
    CGRect rect = [self.view1 convertRect:self.button1.frame toView:self.view];
    self.button1.frame = rect;
    NSLog(@"After: self.button1:%@",self.button1);

執行結果:

Before: self.view:<UIView: 0x8e6f410; frame = (0 0; 320 568); autoresize = RM+BM; layer = <CALayer: 0x8e5c9d0>>

Before: self.view1:<UIView: 0x8e6fc70; frame = (20 91; 245 200); autoresize = W+H; layer = <CALayer: 0x8e6f370>>

Before: self.button1:<UIButton: 0x8e6c930; frame = (102 126; 123 54); opaque = NO; autoresize = RM+BM; layer = <CALayer: 0x8e6cc80>>

After: self.button1:<UIButton: 0x8e6c930; frame = (122 217; 123 54); opaque = NO; autoresize = RM+BM; layer = <CALayer: 0x8e6cc80>>

[iOS] 視圖坐標系轉換2

方法:convertRect:toView

接著是fromView:

    NSLog(@"Before: self.view:%@",self.view);
    NSLog(@"Before: self.view1:%@",self.view1);
    NSLog(@"Before: self.button1:%@",self.button1);
    CGRect rect = [self.view1 convertRect:self.button1.frame fromView:self.view];
    self.button1.frame = rect;
    NSLog(@"After: self.button1:%@",self.button1);

執行結果:

Before: self.view:<UIView: 0x8e6f410; frame = (0 0; 320 568); autoresize = RM+BM; layer = <CALayer: 0x8e5c9d0>>

Before: self.view1:<UIView: 0x8e6fc70; frame = (20 91; 245 200); autoresize = W+H; layer = <CALayer: 0x8e6f370>>

Before: self.button1:<UIButton: 0x8e6c930; frame = (102 126; 123 54); opaque = NO; autoresize = RM+BM; layer = <CALayer: 0x8e6cc80>>

After: self.button1:<UIButton: 0x8e6c930; frame = (82 35; 123 54); opaque = NO; autoresize = RM+BM; layer = <CALayer: 0x8e6cc80>>

方法:convertRect:fromView

方法:convertRect:fromView

會加減的朋友應該可以從位置知道toView和fromView的差別,以後就可以直接利用囉~

上兩個是以面(Rect)為主角,另有兩個方法是以點(Point)為主角,用法大同小異:

  • – (CGPoint)convertPoint:(CGPoint)point toView:(UIView *)view;
  • – (CGPoint)convertPoint:(CGPoint)point fromView:(UIView *)view;

參考:How does – (CGRect)convertRect:(CGRect)rect toView:(UIView *)view work

Advertisements

發表留言

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

您的留言將使用 WordPress.com 帳號。 登出 / 變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 / 變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 / 變更 )

Google+ photo

您的留言將使用 Google+ 帳號。 登出 / 變更 )

連結到 %s

標籤雲

%d 位部落客按了讚: