I have some code that tries to set the backgroundColor in a UIView from an Image but all I see is black screen. Here is what I did -
UIViewController
class and UIView
class UIView
class has a drawRect
function. UIViewController
viewDidLoad
function create the UIView
class drawRect
in the UIView
is called. Here is the code for the 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;
}
Verified in the debugger that the backGround
object is not nil after execution. Also tested the test.png file exists and I can create a UIImageView
with it.
I see that the result is the same if I set the backgroundColor
in the initWithFrame
function instead of the drawRect()
The reason I want to set the backgroundColor
is I am drawing a board game and I want to use the image as the background. That way I can just draw the lines (board) on the image.
- (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;
}
Changing the background in drawRect won't work. Any changes to it must be done in the init method.
just try out this in the viewDidLoad
-(void)viewDidLoad{
UIColor *backGround = [UIColor colorWithPatternImage:[UIImage imageNamed:@"test.png"]];
self.view.backgroundColor = backGround;
//.....
}
EDIT:
For your problem :
the drawing is being done by a layer associated with your view. It looks like, in your environment, the background-colored layer is doing its drawing before your -drawRect:
method is called. When the layer redraws, your -drawRect:
method also happens to be called. So, after you change the background color, you don't see any changes till the background layer draws again, which you can tell happened because your -drawRect: gets called again. ( Here && Check for more info )
In drawRect method you should not set background. You have to do drawing, which you want to draw in view. Background view is separate view. If you want to set the background view within your custom view, do it in init method or else you can do it in your view controller(anywhere).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.