在ImageView android中缩放图像的部分

时间:2012-06-04 13:14:34

标签: android android-imageview

我需要缩放imageView的一部分(比如从x到y),而不是整个图像。 setscaleType()函数恰好适用于整个图像而不是特定部分。 如果有办法在android中进行操作,请告诉我。

先谢谢。

2 个答案:

答案 0 :(得分:5)

你可以通过两种方式实现它。

  1. 创建图像的单独部分(photoshop)
  2. 创建新的位图(rect)并在新的Canvas上绘制并使用它。
  3. 我希望你选择2选项。

答案 1 :(得分:1)

看看

  

public static Bitmap createBitmap(位图源,int x,int y,int   width,int height,Matrix m,boolean filter)

自:API Level 1

从源位图的子集返回不可变位图,由可选矩阵转换。它的初始化密度与原始位图的密度相同。

<强>参数

    source  The bitmap we are subsetting
    x   The x coordinate of the first pixel in source
    y   The y coordinate of the first pixel in source
    width   The number of pixels in each row
    height  The number of rows
    m   Optional matrix to be applied to the pixels
    filter  true if the source should be filtered. Only applies if the matrix contains more than just translation.

<强>返回

A bitmap that represents the specified subset of source

您也可以crop specific portion of image-in-android然后使用createBitmap格式化新的裁剪图像。


使用createBitmap的示例:

public class bitmaptest extends Activity {
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        LinearLayout linLayout = new LinearLayout(this);

        // load the origial BitMap (500 x 500 px)
        Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
               R.drawable.ic_launcher);

        int width = bitmapOrg.getWidth();
        int height = bitmapOrg.getHeight();
        int newWidth = 200;
        int newHeight = 200;

        // calculate the scale - in this case = 0.4f
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;

        // createa matrix for the manipulation
        Matrix matrix = new Matrix();
        // resize the bit map
        matrix.postScale(scaleWidth, scaleHeight);
        // rotate the Bitmap
        matrix.postRotate(45);

        // recreate the new Bitmap
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0,
                          width, height, matrix, true);

        // make a Drawable from Bitmap to allow to set the BitMap
        // to the ImageView, ImageButton or what ever
        BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);

        ImageView imageView = new ImageView(this);

        // set the Drawable on the ImageView
        imageView.setImageDrawable(bmd);

        // center the Image
        imageView.setScaleType(ScaleType.CENTER);

        // add ImageView to the Layout
        linLayout.addView(imageView,
                new LinearLayout.LayoutParams(
                      LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT
                )
        );

        // set LinearLayout as ContentView
        setContentView(linLayout);
    }
}