[英]Relationship between UIVIew and CALayer regarding background image on iOS
試圖了解UIView和CALayer之間的關系。 我閱讀了Apple文檔,但沒有詳細描述兩者之間的關系。
為什么當我添加背景圖像來查看“customViewController.view”時,我得到圖像的不需要的黑色。
當我將背景圖像添加到圖層“customViewController.view.layer”時,圖像的黑色區域消失了(這就是我想要的),但背景圖像是顛倒翻轉的。 這是為什么?
如果我要添加標簽/視圖/按鈕/等。 對於視圖,圖層的背景圖像是否會阻止它們,因為CAlayer由UIView支持?
當您設置UIView的背景顏色時,它會自動設置關聯圖層的背景顏色嗎?
- (void)viewDidLoad { [super viewDidLoad]; customViewController = [[CustomViewController alloc] init]; customViewController.view.frame = CGRectMake(213, 300, 355, 315); customViewController.view.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"login_background.png"]]; // customViewController.view.layer.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"login_background.png"]].CGColor; [self.view addSubview:customViewController.view]; }
視圖中的背景圖片:
- (void)viewDidLoad
{
[super viewDidLoad];
customViewController = [[CustomViewController alloc] init];
customViewController.view.frame = CGRectMake(213, 300, 355, 315);
// customViewController.view.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"login_background.png"]];
customViewController.view.layer.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"login_background.png"]].CGColor;
[self.view addSubview:customViewController.view];
}
在view.layer中的背景圖像:
UIView默認情況下創建為opaque。 將backgroundColor設置為具有透明度的圖案時,選擇黑色作為背景顏色。 你可以設置customViewController.view.opaque = NO;
允許你背后的視圖背景顯示出來。
當您將圖層的backgroundColor設置為具有透明度的圖案時,您將繞過UIView邏輯,因此忽略視圖的不透明度; UIView的改造也是如此。 CoreGraphics和朋友使用坐標系統,其中正y軸指向上方。 UIKit翻轉了這個坐標系。 這就是圖像顛倒的原因。
如果你添加標簽/視圖/按鈕/等。 將在圖層的背景圖案頂部正確顯示。
設置視圖的背景顏色時,看起來好像設置了圖層的背景顏色。 (我沒有在任何地方看到這個記錄)。
基本上UIKit的UIView東西是一個高級界面,最終渲染到圖層上。
希望這可以幫助。
編輯2011年5月7日
你可以通過翻轉圖層的坐標系來讓圖像顯示正確的方向但是你不應該這樣做來查看。 UIKit不希望你弄亂這個圖層,所以如果翻轉它的坐標系,任何UIKit圖形都會被翻轉; 你需要使用一個子層。
所以你的代碼看起來像這樣:
- (void)viewDidLoad
{
[super viewDidLoad];
customViewController = [[CustomViewController alloc] init];
customViewController.view.frame = CGRectMake(213, 300, 355, 315);
CALayer* l = [CALayer layer];
l.frame = customViewController.bounds;
CGAffineTransform t = CGAffineTransformMake(1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f);
l.affineTransform = t;
l.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage
imageNamed:@"login_background.png"]].CGColor;
[customViewController.view.layer addSublayer:l];
[self.view addSubview:customViewController.view];
}
注意:通常在您翻轉坐標時包含高度。 對於圖層,您不需要這樣做。 我沒有挖出為什么會這樣。
正如您所看到的,這里涉及的代碼更多,並且以這種方式實現它並沒有真正的優勢。 我真的建議你堅持使用UIKit方法。 我只是發布了代碼以回應你的好奇心。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.