Search code examples
androidandroid-imageview

Android align top bitmap in imageview


Is there anyway so I can align bitmap in ImageView. I have an issue with my image view. I'm setting it's source via Java Code and after bitmap is resized it's centered in ImageView, but the thing that I want is to align the bitmap.

Declaring the imageView :

    <RelativeLayout
    android:id="@+id/collection_background"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_below="@+id/actionbar" > 


     <ImageView  
        android:id="@+id/collection_image_background"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:background="#ffffff"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:contentDescription="@string/stampii"  />

    // countinue ........

and here is how I'm setting the bitmap :

BitmapFactory.Options o2 = new BitmapFactory.Options();
    o2.inTempStorage = new byte[8*1024];

    ops = BitmapFactory.decodeStream(cis,null,o2);
    ImageView view = (ImageView) findViewById (R.id.collection_image_background);        
    view.setImageBitmap(ops);

Any ides how to do that?


Solution

  • Actually you can scale your bitmap depending on your screen size and set it as source of your ImageView. You can use something like this :

    int screenWidth = getWindow().getWindowManager().getDefaultDisplay().getWidth();
        Log.e("","screen width : "+screenWidth);
        //int screenHeight = getWindow().getWindowManager().getDefaultDisplay().getHeight();
    
        int width = ops.getWidth();
        Log.e("","bitmap width : "+width);
        int height = ops.getHeight();
        Log.e("","bitmap height : "+height);
    
        float scale = 0;
        if(width>height){
            scale = (float) width / (float) height;
        } else if(height>width){
            scale = (float) height / (float) width;
        }
        Log.e("","scale : "+scale);
    
        float newWidth = (float) screenWidth * scale;
    
        Log.d("","new height : "+newWidth);
    
        Bitmap scaledBitmap = Bitmap.createScaledBitmap(ops, screenWidth, (int) newWidth, true);
        Log.e("","new bitmap width : "+scaledBitmap.getWidth());
        Log.e("","new bitmap height : "+scaledBitmap.getHeight());
    
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(screenWidth, (int)newWidth);
        params.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
        view.setLayoutParams(params);
        view.setImageBitmap(scaledBitmap);
    

    Try this and just hit me up if it's working or not.