[英]Setting backgroundColor doesn't seem to work on a UIView
我有一些代碼嘗試從圖像中設置UIView中的backgroundColor,但我看到的只是黑屏。 這是我做的 -
UIViewController
類和UIView
類 UIView
類有一個drawRect
函數。 UIViewController
viewDidLoad
函數中創建UIView
類 UIView
中的drawRect
。 這是UIView
的代碼
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
// Initialization code
}
return self;
}
- (void)drawRect:(CGRect)rect
{
UIColor *backGround = [UIColor colorWithPatternImage:[UIImage imageNamed:@"test.png"]];
self.backgroundColor = backGround;
}
在調試器中驗證了執行后backGround
對象不是nil。 還測試了test.png文件,我可以用它創建一個UIImageView
。
如果我在initWithFrame
函數中設置backgroundColor
而不是drawRect()
我看到結果是一樣的
我想設置backgroundColor
的原因是我正在繪制一個棋盤游戲,我想用圖像作為背景。 這樣我就可以在圖像上繪制線條(板)。
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
// Initialization code
UIColor *backGround = [UIColor colorWithPatternImage:[UIImage imageNamed:@"test.png"]];
self.backgroundColor = backGround;
}
return self;
}
更改drawRect中的背景將不起作用。 對它的任何更改都必須在init方法中完成。
只需在viewDidLoad
嘗試一下
-(void)viewDidLoad{
UIColor *backGround = [UIColor colorWithPatternImage:[UIImage imageNamed:@"test.png"]];
self.view.backgroundColor = backGround;
//.....
}
編輯:
對於你的問題:
繪圖由與視圖關聯的圖層完成。 看起來,在您的環境中,背景色圖層在調用-drawRect:
方法之前正在進行繪制。 重繪圖層時,也會調用-drawRect:
方法。 因此,在更改背景顏色后,在背景圖層再次繪制之前,您看不到任何更改,您可以告訴它,因為您的-drawRect:再次被調用。 ( 這里 && 查看更多信息 )
在drawRect方法中,您不應該設置背景。 你必須做繪畫,你想在視圖中繪制。 背景視圖是單獨的視圖。 如果要在自定義視圖中設置背景視圖,請在init方法中執行,否則可以在視圖控制器中(任何位置)執行此操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.