iOS坑:UIView的frame和transfrom

最近一直在作photoGrid的iOS版本的開發,遇到過不少問題。
目前個人UIView裏有一個UIImageView。
這裏的UIImageView的狀態初始是這樣的: 優化

_imageView = [[UIImageView alloc] init];
_imageView.frame = self.bounds;
_imageView.contentMode = UIViewContentModeScaleAspectFill;
_imageView.autoresizingMask = (UIViewAutoresizingFlexibleHeight |
                               UIViewAutoresizingFlexibleWidth  |
                               UIViewAutoresizingFlexibleTopMargin |
                               UIViewAutoresizingFlexibleLeftMargin|
                               UIViewAutoresizingFlexibleRightMargin |
                               UIViewAutoresizingFlexibleBottomMargin);

由於這個是拼圖軟件,座標都是計算轉換出來的,不免有浮點,而iOS支持的座標最小是 0.5f 的精度。在對外面的UIView和內部的ImageView的座標都進行設置後,咱們發現圖片和圖片之間會有明顯的縫隙,這是爲何呢? 動畫

系統會對UIImageView的座標進行優化,會成爲整型,這樣咱們就看到了Image和Image之間的明顯的縫隙了。 code

那麼如何解決呢? 很簡單,設置一下UIImageView的frame orm

_imageView.frame = self.bounds;

可是這樣作帶來了別的問題。 圖片

由於我在這裏有對這個UIImageView的仿射矩陣作(transform)變換以達到位移、放縮等效果。若是在設置了frame以後再對這個UIImageView作改變仿射矩陣操做,你會發現以前的效果被重置了,若是此時你再去作放縮等操做,都是在原來的基礎上再作的變化。
好比,以前你縮小到0.5倍,而後你會發現圖片會重置到ScaleAspectFit,而後再縮小到0.5倍,此時的仿射矩陣的倍率值(transform.a)就是0.25了,而肉眼觀察到的則是0.5倍的縮放。
哪兒有問題呢? 開發

最後終於在API Document裏面找到這麼一小段話it

// animatable. do not use frame if view 
// is transformed since it will not correctly 
// reflect the actual location of the view. use bounds + center instead.

// 動畫屬性。不要在view變形以後使用frame
// 不然會致使其不能正確的映射出view的真實位置。用bounds + center 代替

好吧,一切釋然了,我檢查了很久的bug竟然只是一句小小的註釋就解決了。io

//_imageView.frame = self.bounds;
_imageView.bounds = self.bounds;
_imageView.center = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height / 2);

OK,正常了!table

相關文章
相關標籤/搜索