Kyle Banks

Repeating Background Image on Android, iPhone, and iPad

Written by @kylewbanks on Feb 28, 2013.

Something that is very common in user interface design is to have a repeating background image on your views. The image is normally very small, and repeats across your view's background to give it more texture or style than a flat background color. This trick is often used for simple gradients, providing better performance than programmatically drawing the gradient on the view, but it can also be used for textures or more complicated gradients to save time coding them. The size of your image will vary based on the complexity of the background, but you will generally want to create the smallest image (square or rectangle) that contains the entire pattern you want to repeat.

Android

In order to achieve this effect, you can use the following code.

View view = (View) findViewById(R.id.my_view);

//Repeating background image
Bitmap backgroundImage = BitmapFactory.decodeResource(getResources(), R.drawable.my_background_image);
BitmapDrawable bitmapDrawable = new BitmapDrawable(getResources(), backgroundImage);
bitmapDrawable.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);  
view.setBackground(bitmapDrawable);

Essentially what you are doing is getting a handle on the image my_background_img, and instructing it to be drawn repeated on the X and Y axis. You then pass these instructions to the view in View.setBackground(Drawable d); and you have successfully created a repeating background image.

Note: Prior to API Level 16, you will need to use View.setBackgroundDrawable(Drawable d);

iPhone and iPad

The code for iOS developers is more or less the same, but with one convenience function for the task.

UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];

//Repeating background image
UIImage *repeatingImage = [UIImage imageNamed:@"my_background_image"];
UIColor *repeatingBackground = [UIColor colorWithPatternImage:repeatingImage];
[myView setBackgroundColor:repeatingBackground];

Notice that + [UIColor colorWithPatternImage:(UIImage *)image]; helps us out by returning a simple UIColor that can be used on any UIView subclass to draw the repeating image.

And there you have it, two simple ways to get a very professional look and feel for your applications on both Android and iOS devices.

Let me know if this post was helpful on Twitter @kylewbanks or down below!