代码之家  ›  专栏  ›  技术社区  ›  Namratha

Android:调整和缩放图像的一部分

  •  2
  • Namratha  · 技术社区  · 16 年前

    给定一个图像,我希望只能缩放该图像的一部分。我想把图像的一半展开,这样,这一半就占了整个空间。

    这怎么可能?

    ImageView fitXY是否可以工作,因为我认为它只适用于整个原始图像。

    @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LinearLayout linearLayout = new LinearLayout(this); 
    
               Bitmap bitmap = BitmapFactory.decodeResource(getResources(),       R.drawable.icon);   
    
    
                int width = bitmap.getWidth();   
    
                 int height = bitmap.getHeight();   
    
                int newWidth = 640;   
    
                int newHeight = 480;   
    
    
                 float scaleWidth = ((float) newWidth) / width;   
    
                float scaleHeight = ((float) newHeight) / height;   
    
    
                Matrix matrix = new Matrix();   
    
                matrix.postScale(scaleWidth, scaleHeight);   
    
                 // create the new Bitmap object   
    
                 Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 50, 50, width,   
    
                         height, matrix, true);   
    
                 BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);   
    
    
    
                 ImageView imageView = new ImageView(this);   
    
                 imageView.setImageDrawable(bmd);   
    
                 imageView.setScaleType(ScaleType.CENTER);   
    
    
    
                 linearLayout.addView(imageView, new LinearLayout.LayoutParams(   
    
                         LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));   
    
                 setContentView(linearLayout);   
      } 
    } 
    

    只有在createBitmap中,源中第一个像素的X和Y坐标为0时,此操作才有效。也就是说,我无法提取图像的一个子集。只能缩放整个图像。但是createBitmap是用来对图像进行子集的。

    在日志中,当参数不是0时,我得到以下异常:java.lang.IllegalArgumentException:x+宽度必须为<=位图.width()

    请帮忙

    2 回复  |  直到 14 年前
        1
  •  2
  •   Chandra Sekhar    14 年前

    首先,必须使用要缩放的部分创建新位图

    createBitmap() //pass the source bitmap, req height and width
    

    现在从结果位图中,您必须使用

    createScaledbitmap() //pass the result bitmap , req width, height
    

    例如:

    Bitmap originalBitmap = BitmapFactory.decodeResource(res, id);
    Bitmap partImage = originalBitmap.createBitmap(width, height, config);
    Bitmap scaledImage = partImage.createScaledBitmap(partImage, dstWidth, dstHeight, filter);
    
        2
  •  1
  •   Andro Selva Anand Wadhwani    14 年前

    所以我不得不修改了几个拼写错误,但是这个例子对我很好。 http://www.anddev.org/resize_and_rotate_image_-_example-t621.html 输入错误:

    int width = bitmapOrg.width();
    int height = bitmapOrg.height();
    

    变成:

    int width = bitmapOrg.getWidth();
    int height = bitmapOrg.getHeight();
    

    否则,当我再次尝试SDK 7时

    推荐文章