Sunday, 22 March 2009

Drawing in views : background in custom views

Sometimes it could be usefull to have a background image in view instead of a color. For example if we want to have a texture in a view.

In the following example I draw a 'wall' as the background of a view :

The texture I want to apply to my view is the following :

Now its very easy to define this as a texture, you just create a new color , and not just a color but a colorpattern :

Step 1 : find the texture in my resources

NSString* fileName = [[NSBundle mainBundle] pathForResource: @"wall" ofType:@"jpg"];

NSURL* url = [NSURL fileURLWithPath: fileName];

Step 2 : upload the image from the URL
background = [[NSImage alloc] initWithContentsOfURL: url];

Step 3 : define a new color

color = [NSColor colorWithPatternImage:background ] ;
[color set] ;

Step 4 : fill the background
NSRectFill( [self bounds] ) ;

Note that you need to implement this code also in the drawRect: method, to ensure that each time your view get's redrawn that the background is drawn also.

No comments:

Post a Comment