Nassif
Nassif

Reputation: 1223

Image Repetition in ios siimilar to CSS background-repeat function

Is it possible to repeat an image in ios similar to CSS function

background-image:imageurl;
background-repeat :repeat-x;

so that an image is perfectly scaled for iphone and iPad screen sizes

Upvotes: 1

Views: 448

Answers (2)

uchuugaka
uchuugaka

Reputation: 12782

You have loads of options. Core Graphics gives you CGContextDrawTiledImage()

UIImage gives you drawPatternInRect: (Probably a wrapper of the above )

But the most useful thing is to look at transformations. CGAffineTransform in the Quartz 2D Drawing guide is the thing you want to read about.

It's pretty cheap and easy in draw rect to just do some iteration that draws the same image at a bunch of locations that are in CG terms translations of the image, meaning it's drawn at another place.

You can even draw to an image context before drawing to a view and get a cached representation so you don't need to always redraw every thing.

Core Animation has transforms as well.

Upvotes: 0

verec
verec

Reputation: 5294

You could try this:

- (UIImage *) imageFromAssetImageNamed: (NSString *) name {
    NSString * fullKeyPath = [[NSBundle mainBundle] pathForResource:name
                                                             ofType:@"png"
                                                        inDirectory:@"assets"] ;

    return [UIImage imageWithContentsOfFile:fullKeyPath] ;
}

- (UIColor *) colorPatternFromAssetImageNamed: (NSString *) name {

    return [UIColor colorWithPatternImage:[self imageFromAssetImageNamed:name]] ;
}

You can then set the background color, for example, using:

self.window.backgroundColor = [self colorPatternFromAssetImageNamed:@"my-bg-color"] ;

You will still need to adjust the frame to control how much of the width/height is covered.

Upvotes: 1

Related Questions