Use an ImageView to Show a Raster Graphic
Showing a bitmap image, such as a Portable Network Graphics (PNG) or JPEG file, in an Android application (App) is easy. In this tutorial we show you how. It is assumed you are programming in Java using the Android SDK from within the Eclipse Integrated Development Environment (IDE). For PC users starting out in Android Java development see Set Up Windows for Android Development to prepare your development environment.
The ImageView class can be used and pointed at a bitmap stored under one of the drawable folders in the res project folders. Let us start by creating a very basic App project that will contain the ImageView and bitmap to display. If you do not know how to create a basic Android project in Eclipse see the article Your First Android Program. With Eclipse open select the File menu then New and Android Application Project. In the New Android App wizard the fields are set as follows:
- Application Name – Bitmap
- Project Name – Bitmap
- Package Name – biz.tekeye.bitmap
- Build SDK – Android 4.1 (API 16)
- Minimum Required SDK – API 3: Android 1.5 (Cupcake) – or the lowest one installed
- Create custom launcher icon – unchecked
- Mark this project as a library – unchecked
- Create project in Workspace – checked
Press the Next button. Create Activity should be checked and BlankActivity selected. Press the Next button again. On the New Blank Activity screen leave the fields as default and press Finish. The Bitmap project will be created and the App’s initial screen will load in the graphical designer.
The next task is to add the bitmap. For this example we are using a clown PNG file. You can use your own PNG or JPEG file or download this clown bitmap which is in the Public Domain. In Eclipse use the Package Explorer to expand the Bitmap project folder (if Package Explorer is not open use the Window then Show View or Reset Perspective menu options). With the res folder selected use the File menu (or context menu) then select New and Folder menu option. The Folder name is set to drawable. Copy the clown PNG file into the res/drawable folder (drag and drop works).
In Eclipse, with the Graphical Layout shown for res/drawable/layout/activity_main.xml, open the Images & Media folder in the Palette. Drag an ImageView (should be the first item) onto the layout. The Resource Chooser dialog will appear and the clown bitmap can be selected.
The Android App is ready to run! Delete the TextView that is displaying the Hello World! message. Press the run button and view the result on an AVD (see Set Up an Android Virtual Device for App Testing) or a physical device plugged into the PC.