This activity demonstrates various ways density can cause the scaling of bitmaps and drawables. : Bitmap « 2D Graphics « Android






This activity demonstrates various ways density can cause the scaling of bitmaps and drawables.

    
/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package app.test;

import android.app.Activity;
import android.os.Bundle;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ScrollView;
import android.view.LayoutInflater;
import android.view.View;
import android.content.Context;
import android.util.DisplayMetrics;
import android.util.Log;

/**
 * This activity demonstrates various ways density can cause the scaling of
 * bitmaps and drawables.
 */
public class DensityActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        final LayoutInflater li = (LayoutInflater)getSystemService(
                LAYOUT_INFLATER_SERVICE);

        this.setTitle("density_title");
        LinearLayout root = new LinearLayout(this);
        root.setOrientation(LinearLayout.VERTICAL);

        LinearLayout layout = new LinearLayout(this);
        addBitmapDrawable(layout, R.drawable.logo120dpi, true);
        addBitmapDrawable(layout, R.drawable.logo160dpi, true);
        addBitmapDrawable(layout, R.drawable.logo240dpi, true);
        addLabelToRoot(root, "Prescaled bitmap in drawable");
        addChildToRoot(root, layout);

        layout = new LinearLayout(this);
        addBitmapDrawable(layout, R.drawable.logo120dpi, false);
        addBitmapDrawable(layout, R.drawable.logo160dpi, false);
        addBitmapDrawable(layout, R.drawable.logo240dpi, false);
        addLabelToRoot(root, "Autoscaled bitmap in drawable");
        addChildToRoot(root, layout);

        layout = new LinearLayout(this);
        addResourceDrawable(layout, R.drawable.logo120dpi);
        addResourceDrawable(layout, R.drawable.logo160dpi);
        addResourceDrawable(layout, R.drawable.logo240dpi);
        addLabelToRoot(root, "Prescaled resource drawable");
        addChildToRoot(root, layout);

        layout = (LinearLayout)li.inflate(R.layout.density_image_views, null);
        addLabelToRoot(root, "Inflated layout");
        addChildToRoot(root, layout);

        layout = (LinearLayout)li.inflate(R.layout.density_styled_image_views, null);
        addLabelToRoot(root, "Inflated styled layout");
        addChildToRoot(root, layout);

        layout = new LinearLayout(this);
        addCanvasBitmap(layout, R.drawable.logo120dpi, true);
        addCanvasBitmap(layout, R.drawable.logo160dpi, true);
        addCanvasBitmap(layout, R.drawable.logo240dpi, true);
        addLabelToRoot(root, "Prescaled bitmap");
        addChildToRoot(root, layout);

        layout = new LinearLayout(this);
        addCanvasBitmap(layout, R.drawable.logo120dpi, false);
        addCanvasBitmap(layout, R.drawable.logo160dpi, false);
        addCanvasBitmap(layout, R.drawable.logo240dpi, false);
        addLabelToRoot(root, "Autoscaled bitmap");
        addChildToRoot(root, layout);

        layout = new LinearLayout(this);
        addResourceDrawable(layout, R.drawable.logonodpi120);
        addResourceDrawable(layout, R.drawable.logonodpi160);
        addResourceDrawable(layout, R.drawable.logonodpi240);
        addLabelToRoot(root, "No-dpi resource drawable");
        addChildToRoot(root, layout);

        layout = new LinearLayout(this);
        addNinePatchResourceDrawable(layout, R.drawable.smlnpatch120dpi);
        addNinePatchResourceDrawable(layout, R.drawable.smlnpatch160dpi);
        addNinePatchResourceDrawable(layout, R.drawable.smlnpatch240dpi);
        addLabelToRoot(root, "Prescaled 9-patch resource drawable");
        addChildToRoot(root, layout);

        setContentView(scrollWrap(root));
    }

    private View scrollWrap(View view) {
        ScrollView scroller = new ScrollView(this);
        scroller.addView(view, new ScrollView.LayoutParams(ScrollView.LayoutParams.MATCH_PARENT,
                ScrollView.LayoutParams.MATCH_PARENT));
        return scroller;
    }

    private void addLabelToRoot(LinearLayout root, String text) {
        TextView label = new TextView(this);
        label.setText(text);
        root.addView(label, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
    }

    private void addChildToRoot(LinearLayout root, LinearLayout layout) {
        root.addView(layout, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
    }

    private void addBitmapDrawable(LinearLayout layout, int resource, boolean scale) {
        Bitmap bitmap;
        bitmap = loadAndPrintDpi(resource, scale);

        View view = new View(this);

        final BitmapDrawable d = new BitmapDrawable(getResources(), bitmap);
        if (!scale) d.setTargetDensity(getResources().getDisplayMetrics());
        view.setBackgroundDrawable(d);

        view.setLayoutParams(new LinearLayout.LayoutParams(d.getIntrinsicWidth(),
                d.getIntrinsicHeight()));
        layout.addView(view);
    }

    private void addResourceDrawable(LinearLayout layout, int resource) {
        View view = new View(this);

        final Drawable d = getResources().getDrawable(resource);
        view.setBackgroundDrawable(d);

        view.setLayoutParams(new LinearLayout.LayoutParams(d.getIntrinsicWidth(),
                d.getIntrinsicHeight()));
        layout.addView(view);
    }

    private void addCanvasBitmap(LinearLayout layout, int resource, boolean scale) {
        Bitmap bitmap;
        bitmap = loadAndPrintDpi(resource, scale);

        ScaledBitmapView view = new ScaledBitmapView(this, bitmap);

        view.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        layout.addView(view);
    }

    private void addNinePatchResourceDrawable(LinearLayout layout, int resource) {
        View view = new View(this);

        final Drawable d = getResources().getDrawable(resource);
        view.setBackgroundDrawable(d);

        Log.i("foo", "9-patch #" + Integer.toHexString(resource)
                + " w=" + d.getIntrinsicWidth() + " h=" + d.getIntrinsicHeight());
        view.setLayoutParams(new LinearLayout.LayoutParams(
                d.getIntrinsicWidth()*2, d.getIntrinsicHeight()*2));
        layout.addView(view);
    }

    private Bitmap loadAndPrintDpi(int id, boolean scale) {
        Bitmap bitmap;
        if (scale) {
            bitmap = BitmapFactory.decodeResource(getResources(), id);
        } else {
            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inScaled = false;
            bitmap = BitmapFactory.decodeResource(getResources(), id, opts);
        }
        return bitmap;
    }

    private class ScaledBitmapView extends View {
        private Bitmap mBitmap;

        public ScaledBitmapView(Context context, Bitmap bitmap) {
            super(context);
            mBitmap = bitmap;
        }

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            final DisplayMetrics metrics = getResources().getDisplayMetrics();
            setMeasuredDimension(
                    mBitmap.getScaledWidth(metrics),
                    mBitmap.getScaledHeight(metrics));
        }

        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);

            canvas.drawBitmap(mBitmap, 0.0f, 0.0f, null);
        }
    }
}

//layout/density_image_views.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2009 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <ImageView style="@style/ImageView120dpi" />
    <ImageView style="@style/ImageView160dpi" />
    <ImageView style="@style/ImageView240dpi" />

</LinearLayout>


//layout/density_styled_image_views

<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2009 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/reslogo120dpi" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/reslogo160dpi" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/reslogo240dpi" />

</LinearLayout>

   
    
    
    
  








Related examples in the same category

1.Using BitmapFactory to decode Resource
2.Capture and save to Bitmap
3.Bitmap size
4.Draw Bitmap on Canvas
5.Bitmap.createBitmap
6.Draw Bitmap on Canvas with Matrix
7.Create a Bitmap for drawing
8.Load Bitmap and Draw
9.Bitmap and RenderScript
10.Alpha Bitmap
11.Load Bitmap from InputStream
12.Bitmap Decode
13.Bitmap Mesh
14.Bitmap Pixels
15.Create a Bitmap
16.Bitmap.Config.ARGB_8888,Bitmap.Config.RGB_565, Bitmap.Config.ARGB_4444
17.Purgeable Bitmap
18.Create a bitmap with a circle
19.Get the current system wallpaper, modifies it and sets the modified bitmap as system wallpaper.
20.Bitmap cache by WeakHashMap
21.Memory Cache for Bitmap
22.Load Bitmap from resource
23.Crop Bitmap
24.Create Scaled Bitmap
25.downloading a bitmap image from http and setting it to given image view asynchronously
26.Get Bitmap From Local Path
27.Get Bitmap From Bytes
28.Compress Bitmap
29.Resize Bitmap
30.captures given view and converts it to a bitmap
31.Save Bitmap and BitmapFactory.decodeFile
32.Generate a blurred bitmap from given one
33.Get Bitmap From Name
34.Load Bitmap with Context
35.Load Bitmap from InputStream
36.Get Bitmap from Url with HttpURLConnection
37.Rotate Bitmap
38.Get Texture From Bitmap Resource and BitmapFactory.decodeStream
39.Drawable to Bitmap
40.Save Bitmap to and load from External Storage
41.Get Image Bitmap From Url
42.Scale Bitmap
43.Unscaled Bitmap Loader
44.Save Bitmap to External Storage Directory
45.Compress and save Bitmap image
46.Bitmap downloading, processing
47.Rotate a Bitmap
48.Save/load Bitmap
49.Find components of color of the bitmap at x, y.
50.get Bitmap From Url
51.Draw Bitmap and Drawable
52.Rotate, transform Bitmap
53.Rotate specified Bitmap by a random angle. Scales the specified Bitmap to fit within the specified dimensions.
54.Loads a bitmap from the specified url.
55.Bitmap Refelection
56.Create a transparent bitmap from an existing bitmap by replacing certain color with transparent
57.Get Texture From Bitmap Resource
58.Bitmap Resize
59.bitmap to Byte
60.Flip Image
61.Scale an Image
62.Translate Image
63.Image Mirror
64.Moving an Image with Motion
65.Draw on Picture and save
66.Calculate optimal preview size from given parameters
67.generate Mipmaps For Bound Texture
68.Provides common tools for manipulating Bitmap objects.