How to tile a background image in Android

How to tile a background image in Android


For one of the apps I'm working on I wanted to have a nice pixel pattern tiled behind my widgets.
After a little bit of hunting around I found  this tutorial, and I thought I'd clean up the lessons within and show you how.

Here's the contents of my main.xml layout file,

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/backrepeat"
    android:gravity="center_horizontal"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />  
</LinearLayout>



which is referenced in code in the standard way like this:

main);
...// (rest of onCreate method continues here..)

Now note this line:

android:background="@drawable/backrepeat"


What's going on there?
.. Glad you asked!

Here's a quick screenshot of the contents of one of my drawable folders in my project:


What is this 
backrepeat.xml?

Well, here's the contents of that file here:

<bitmap
xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/scale1"
android:tileMode="repeat"
android:dither="true" />



Can you see what's going on?
Backrepeat.xml defines an instance of the  BitmapDrawable class, and that class references our simple scale1.jpg, located in the drawable-hdpi folder.

Simply by adding the:

<bitmap
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/scale1"
    android:tileMode="repeat"
    android:dither="true" />

line in bold, we are able to achieve results such as this:



Easy isn't it?

One thing to keep in mind is that you should have folders drawable-hdpi, drawable-mdpi & drawable-ldpi, you'll need to add this backrepeat.xml file and the relevant images to each of these to allow this functionality in high, medium and low dpi (dots per inch) screen sizes.

Enjoy.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值