Androud图片放大缩小处理

private ImageView big_image;   
    /*
     * 原图片宽   原图片高
     */
    private int primary_width, primary_height;   
    /*
     * 高宽比例
     */
    private double scaleWidth = 1, scaleHeight = 1; 
    private Bitmap bitmap;
    float scale = 0.2f;
    private Button big_button, small_button;
    @Override
    protected void onCreate(Bundle instance)
    {
        super.onCreate(instance);
        setContentView(R.layout.big);
        initResource();
        setListener();
    }
    private void setListener()
    {
        big_button.setOnClickListener(big_button_listener);
        small_button.setOnClickListener(small_button_listener);
    }
    private OnClickListener big_button_listener = new OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            scale(1.25,1.25);
        }
    };
    private OnClickListener small_button_listener = new OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            scale(0.8,0.8);
        }
    };
    private void initResource()
    {
        big_button = (Button) findViewById(R.id.big_button);
        small_button = (Button) findViewById(R.id.small_button);
        bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.c1);
       
        primary_width = bitmap.getWidth();
        primary_height = bitmap.getHeight();
       
        big_image = (ImageView) findViewById(R.id.big_image);
        big_image.setImageBitmap(bitmap);
    }
    private void scale(double  scale_width, double scale_height)
    { 
        Display display = getWindowManager().getDefaultDisplay();
       
        big_image = (ImageView) findViewById(R.id.big_image);
        int re_width = big_image.getWidth();
        int re_height = big_image.getHeight();
        if((scale_width > 1 && scaleWidth * re_width >= display.getWidth())  ||
           (scale_height > 1 && scaleHeight * re_height >= display.getHeight()))
        { 
            big_button.setEnabled(false); 
        }
        else
        { 
            big_button.setEnabled(true); 
        } 
        scaleWidth = scaleWidth * scale_width; 
        scaleHeight = scaleHeight * scale_height; 
         
        /*
         * 矩阵,用于图片比例缩放
         */
        Matrix matrix = new Matrix();
        /*
         * 设置高宽比例(三维矩阵)
         */
        matrix.postScale((float)scaleWidth, (float)scaleHeight);    
         
        /*
         * 参数说明:
         * Bitmap source:要从中截图的原始位图
         * int x:起始x坐标
         * int y:起始y坐标
         * int width:要截的图的宽度
         * int height:要截的图的宽度
         * boolean filter:
         * 返回值:返回一个剪切好的Bitmap
         */
        Bitmap newBmp = Bitmap.createBitmap(bitmap, 0, 0, primary_width, primary_height, matrix, true);  

        big_image.setImageBitmap(newBmp); 
    }

猜你喜欢

转载自mickey-hou.iteye.com/blog/1627209