tags:

views:

147

answers:

2

On the iPhone, how could I achieve the same tiled background effect?

For example, I have an pattern image which I want to repeat only horizontally. Would I have to go the route in -drawRect: by myself and loop over to draw the pattern, or is there a convenient method to do that?

+3  A: 
- (void)drawRect:(CGRect)rect 
{
    CGContextRef    currentContext      = UIGraphicsGetCurrentContext();

    UIImage* img = [UIImage imageNamed:@"transparency.png"];
    CGContextDrawTiledImage(currentContext, CGRectMake(0, 0, 12, 12), [img CGImage]);
}

In this example "transparency.png" is a 12x12 image.

CJ
+4  A: 

You can set the backgroundColor of the UIView with a pattern using the following snippet:

UIImage *image = [UIImage imageNamed:@"pattern.png"];
myView.backgroundColor = [UIColor colorWithPatternImage:image];

The image will automatically be tiled for you to cover the area.

Claus

Claus Broch
thanks Claus, that works great. But unfortunately transparency in the image turns black with this.
dontWatchMyProfile
Is the view the backmost view, or do you have a non-transparent view behind this one?
Claus Broch
I prefer your solution, Claus. Thank you :)
Emil
I hav no transparent view behind it. It is a subview of the colorful superview with images and background color...
dontWatchMyProfile
Odd. Have you verified that the png file actually contains a transparent image. How does it display in e.g. Photoshop and Preview?
Claus Broch