ImageView Zoom and Scroll

Update: the source code has moved to github, so it’s easier for anyone to fork it!

As long as Android doesn’t have a built-in ImageView widget with zoom and scroll capabilities I tries to create one by myself starting from the google repository.

The result is pretty nice so I’m posting here the source code, if anyone is interested, or simply doesn’t want to waste the time creating a new one.

Here’s a sample code on how to use it in an Activity:


Anyway, if you want to download the source, here is the eclipse source project:…/

import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore.Images;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
public class ImageZoomActivity extends Activity {
	private ImageViewTouch mImageView;
	protected void onCreate( Bundle savedInstanceState )
		super.onCreate( savedInstanceState );
		requestWindowFeature( Window.FEATURE_NO_TITLE );
		setContentView( R.layout.main );
		getWindow().addFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN );
	public void onContentChanged()
		mImageView = (ImageViewTouch)findViewById( );
	 * pick a random image from your library
	 * and display it
	public void selectRandomImage()
		Cursor c = getContentResolver().query( Images.Media.EXTERNAL_CONTENT_URI, null, null, null, null );
		if ( c != null ) {
			int count = c.getCount();
			int position = (int)( Math.random() * count );
			if ( c.moveToPosition( position ) ) {
				long id = c.getLong( c.getColumnIndex( Images.Media._ID ) );
				int orientation = c.getInt( c.getColumnIndex( Images.Media.ORIENTATION ) );
				Uri imageUri = Uri.parse( Images.Media.EXTERNAL_CONTENT_URI + "/" + id );
				Bitmap bitmap;
				try {
					bitmap = ImageLoader.loadFromUri( this, imageUri.toString(), 1024, 1024 );
					mImageView.setImageBitmapReset( bitmap, orientation, true );
				} catch ( IOException e ) {
					Toast.makeText( this, e.toString(), Toast.LENGTH_LONG ).show();
			c = null;

Widget: SlidingDrawer top to bottom

My android experiments continue…
In the last project I had to implement a SlidingDrawer which comes from top and left. The problem was that the default widget does not support all the directions, but only bottom to top and right to left.

That’s why I grabbed the SlidingDrawer source code and modified it in order to allow any direction ( defined as styleable in attrs.xml ). The only problem using custom styleable xml is that if you want to use this widget as library you need to include in the main project also the attrs.xml file as well.. a bit frustrating.

Anyway this is just the sample xml how to include the widget:

Btw If you’re interest, here you can find the full source code of the widget including a running application:

SlidingDrawer Demo 

* Updated the code thanks to Maciej Ciemięga.

Multipage TIF to PDF

Recently I’ve continued the porting of iText adding the support for a new image type: multipage tif.

The only problem with this update is that actually it’s really slow and probably with very complex image files it can hang the player for too long. Probably I should modify the ImageElement.getInstance method and make it asynchronous in order to prevent flash player to freeze…

Anyway, the current trunk version of purePDF can handle TIF image and here a simple code example:

import flash.display.Sprite;
import flash.utils.ByteArray;
import flash.utils.Timer;
import flash.utils.getQualifiedClassName;

import org.purepdf.elements.RectangleElement;
import org.purepdf.elements.images.ImageElement;
import org.purepdf.pdf.PageSize;
import org.purepdf.pdf.PdfDocument;
import org.purepdf.pdf.PdfViewPreferences;
import org.purepdf.pdf.PdfWriter;
import org.purepdf.pdf.codec.TiffImage;

public class TestTIF extends Sprite
[Embed( source="assets/foxdog_multiplepages.tif", mimeType="application/octet-stream" )]
private var cls1: Class;

private var document: PdfDocument;
private var writer: PdfWriter;
private var buffer: ByteArray;
private var filename: String;
private var index: int;
private var pages: int;
private var stream: RandomAccessFileOrArray;

public function TestTIF()
addEventListener( Event.ADDED_TO_STAGE, onAdded );

private function onAdded( event: Event ): void
stage.addEventListener( MouseEvent.CLICK, onClick );

private function createDocument( subject: String = null, rect: RectangleElement = null ): void
buffer = new ByteArray();

if ( rect == null )
rect = PageSize.A4;
writer = PdfWriter.create( buffer, rect );
document = writer.pdfDocument;
document.addTitle( getQualifiedClassName( this ) );

if ( subject )
document.addSubject( subject );
document.setViewerPreferences( PdfViewPreferences.FitWindow );

private function onClick( event: Event ): void
filename = getQualifiedClassName( this ).split( "::" ).pop() + ".pdf";
var byte: ByteArray = new cls1();
stream = new RandomAccessFileOrArray( byte );
var image: ImageElement = ImageElement.getInstance( byte );
createDocument( "Multi page TIFF Image Example", PageSize.A4 );;
// add the first page to the document
document.add( image );
// get the total number of pages
pages = TiffImage.getNumberOfPages( stream );
trace("number of pages: " + pages );
// next page index to add to document (first page is 1)
index = 2;
var timer: Timer = new Timer( 100, 1 );
timer.addEventListener( TimerEvent.TIMER, onTimerComplete );

private function onComplete(): void

private function onTimerComplete( event: TimerEvent ): void
if ( index > pages )
document.add( TiffImage.getTiffImage( stream, index ) );
Timer( ).reset();
Timer( ).start();

private function save( e: * = null ): void
var f: FileReference = new FileReference(); buffer, filename );

Here you can see the result PDF file.
And here the input TIF image.

purePDF and transparent BitmapData

Recently I’ve updated purePDF to a new version fixing one bug which caused problems with PNG images.
However when you’re trying to add BitmapData with transparency  to a pdf document you probably get black backgrounds to your images. This is because internaly purePDF converts bitmapdata into 24bit tiff images, so no alpha informations.

This is a script you can use to convert your BitmapData images into transparent pdf ImageElements:

* Create a transparent ImageElement
* An ImageElement with the input bitmapdata RGB informations will be
* created and an ImageElement will be used as mask ( using the alpha info from the bitmapdata )
* If the input bitmapdata is not transparent a regular ImageElement will be returned.
protected function createTransparentImageElement( bitmap: BitmapData ): ImageElement
var output: ByteArray = new ByteArray();
var transparency: ByteArray = new ByteArray();
var input: ByteArray = bitmap.getPixels( bitmap.rect );
input.position = 0;

while( input.bytesAvailable ){
const pixel: uint = input.readInt();

// write the RGB informations
output.writeByte( (pixel >> 16) & 0xff );
output.writeByte( (pixel >> 8) & 0xff );
output.writeByte( (pixel >> 0) & 0xff );

// write the alpha informations
transparency.writeByte( (pixel >> 24) & 0xff );

output.position = 0;
transparency.position = 0;

var mask: ImageElement = ImageElement.getRawInstance( bitmap.width, bitmap.height, 1, 8, transparency, null );
var image: ImageElement = ImageElement.getRawInstance( bitmap.width, bitmap.height, 3, 8, output, null );

if( bitmap.transparent )
image.imageMask = mask;
return image;

and here there’s a demo app:

Android experiments

As you probably understood during last days I’m completely absorbed in Android development.
While experimenting new things ( it remembers to me the first days with Flash 🙂 ) I did a couple of applications and I’ve published them to the market ( it takes less than one hour to be published on the market, just some weeks less than on the app store ).

First one is a simple note application, very similar to the iPhone note app. This one was for testing the ContentProvider and the built-in android search feature.
Second one is for view, search, plan routes for the Milan subway. This is a mix of features: google maps api, layar intergration, gps locations..

How-to debug native code with Android

This is a step by step guide for executing and debugging native code on Android with Eclipse.

1. Prerequisites

The SDK version used for this guide is Froyo with the NDK r4b ( crystax release ).
Also Eclipse CDT plugin it’s very useful for our purposes, so install it.
Last plugin to install it’s the Sequoyah plugin for Eclipse.

2. Project setup

At this point let’s create a new Android project, name it “Example” and use the “” package name, add also an Activity name of your choice.
Select Android 2.2 as base SDK version and complete the project wizard.

Now you need to add the native support for the newly created project. Just right click on the project root element in the package explorer and select “add native support”.

In the next dialog write the path of your NDK folder and give also name for your library.
After this operation a new folder “jni” will be created with a .cpp file, header filer and an Android makefile,, which can be edited to modify all the includes, linker and compiler options. In the file you also need to specify all the source file you want to use within the LOCAL_SRC_FILE directive.

3. Debug

In order to enable debug of native code in Android you have to face different problems, based also on the device and the firmware version, and if the native code is multi thread or single thread.
First of all you need to mofify the AndroidManifest.xml file adding the attribute “debuggable” to true ( remember also to enable the “Debug USB” option under the Application device menu ).
At this point you can debug all the java code within your eclipse debugger, for for the native C debug you need more steps.

Continue reading

Playing with a LocalActivityManager bug

If you already used the ActivityGroup class you probably used also the LocalActivityManager instance to manage your group’s activities. I was creating my activity which should also manages its internal history ( using a ViewFlipper for animating the activity views ).
The problem came out once I tried to destroy an activity from the history using the LocalActivityManager destroy method. After an activity was removed from both my internal history and from the local activity manager I was unable to create a new instance of the same activity.

After googling for my problem I found that it was because a bug in the LocalActivityManager class:
This is exactly my problem! In fact, debugging the android code ( see this post for debugging android code ) at that point it was clear that the record it’s not removed from the internal mActivities map.

Fortunately there are Reflections which can help me! I added this piece of code after the call to the destroy method:

Field mActivitiesField = getLocalActivityManager().getClass().getDeclaredField( "mActivities" );
mActivitiesField.setAccessible( true );
((Map) mActivitiesField.get( getLocalActivityManager() )).remove( id );

and that trick does the job

Reading resource files from native code

If you’re working with android-ndk and you want to open an asset included in your apk package, you should make a request via jni to the Resource manager in your java code.
Something like:

public int[] openAsset( String path )
AssetFileDescriptor ad = null;
ad = getResources().getAssets().openFd( path );
Integer off = (int) ad.getStartOffset();
Integer len = (int) ad.getLength();
int res[] = { off, len };
return res;
} catch( IOException e ) {
Log.e( TAG, e.toString() );
return null;

However this is not a optimal solution expecially when you have tons of file io operations, also because I prefer to limit the amount of calls between java and C++.
A better solution I’m using is to open the current apk application using the libzip library. Just download the library and compile as static library, then include it in your make file under the LOCAL_STATIC_LIBRARIES section.
What you have to do first is to send the current application filename from java, once at startup, in this way:

PackageInfo info = null;
try {
info = getContext().getPackageManager().getPackageInfo(“com.example.text”, 0);
} catch( NameNotFoundException e ) {
Log.e( TAG, e.toString() );
setAppName( info.applicationInfo.sourceDir );

and in the C++ code you will have the corresponding setAppName method:


char packageName[1024] = {0};
zip *pkg_zip;

JNIEXPORT void JNICALL Java_com_example_test_MySurfaceView_setAppName( JNIEnv * env, jobject obj, jstring pkgname )
const char *buffer = env->GetStringUTFChars( pkgname, false );

int error;
pkg_zip = zip_open( buffer, 0, &error );
strcpy( packageName, buffer );
if( pkg_zip == NULL ){
LOGE(“Failed to open apk: %i”, error );
env->ReleaseStringUTFChars( pkgname, buffer );

Now you have a reference to the zip package. In this way now you can query the zip package asking if a particular file exists:

bool FileExists(const char* fname)
if( pkg_zip != NULL )
int result = zip_name_locate( pkg_zip, fname, 0);
return result != -1;
return false;

And open any of the files included in your apk package:

FILE *FileOpen( const char* fname )
zip_file *zfile = zip_fopen( pkg_zip, fname, 0 );
uint32_t offset = 0;
uint32_t length = 0;

if( zfile != NULL )
offset = zfile->fpos;
length = zfile->bytes_left;
zip_fclose( zfile );
zfile = NULL;
} else
return NULL;

FILE *fp = NULL;
fp = fopen( packageName, “rb” );
fseek( fp, offset, SEEK_SET );
return fp;

Using this method you will have a FILE pointer to the whole apk file so you have to take care of the offset and length field when reading and seeking the file itself.