使用画布绘制后缩放位图

时间:2013-05-29 23:57:18

标签: android bitmap android-imageview android-canvas

我正在尝试拍摄相机的预览并在其上绘制一个矩形(当用户选择一个区域时我得到它的坐标)但是当我在ImageView中显示照片时,它会缩放(更大的尺寸)。详细说明:

1_我的主要布局是一个LinearLayout,它包含一个FrameLayout,而FrameLayout又包含相机预览
2_在我的活动中,我有android.hardware.Camera的实例,并且我已将其与PictureCallback实例相关联,并实施了onPictureTaken方法来获取位图:

BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inPurgeable = true;            
        opts.inInputShareable = true;
        opts.inScaled = false;
        bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts);


3_拍摄照片后,用户选择一个区域,我将这些坐标用于绘制矩形:

preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mCameraPreview);//mCameraPreview is an instance of "CameraPreview extends SurfaceView implements SurfaceHolder.Callback"
preview.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View view, MotionEvent me) {
    /* read the coordinates x1, y1, x2, y2 */

    //the commented code was already tested, same result        
    //Bitmap tempBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.RGB_565);
    Bitmap tempBitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), bitmap.getHeight(), true);
    Canvas canvas = new Canvas(tempBitmap);
    Paint paint = new Paint();
    paint.setColor(Color.GREEN);
    canvas.drawLine(x1, y1, x2, y1, paint);
    canvas.drawLine(x1, y1, x1, y2, paint);
    canvas.drawLine(x1, y2, x2, y2, paint);
    canvas.drawLine(x2, y1, x2, y2, paint);
    ImageView imageView = new ImageView(CameraActivity.this);
    imageView.setImageBitmap(tempBitmap);
    //the commented code was already tested, same result    
    //imageView.setImageDrawable(new BitmapDrawable(getResources(), tempBitmap)); 
    imageView.draw(canvas);
    LayoutParams lp = new LayoutParams(tempBitmap.getWidth(), tempBitmap.getHeight());
    imageView.setLayoutParams(lp);
    preview.addView(imageView);
    }
}

最终结果是绘制了矩形,但位图比原始位置大得多,你知道为什么吗? 提前谢谢。
PS:我在构建tempBitmap时尝试了bitmap.getWidth()/ 2,图像几乎是原始大小,但矩形也缩小了。

编辑:我已尝试使用imageView.setAdjustViewBounds(true)imageView.setScaleType(ImageView.ScaleType.FIT_CENTER)(同时使用ScaleType.CENTER,CENTER_CROP,FIT_XY和MATRIX)。有人知道什么是hapenning ???

1 个答案:

答案 0 :(得分:0)

默认情况下,图像视图在位图上应用缩放以使位图适合imageview的整个区域;

试试此代码

ImageView imageView = new ImageView(CameraActivity.this);
imageView .setImageMatrix (new Matrix());
imageView .setScaleType(ImageView.ScaleType.MATRIX);
imageView.setImageBitmap(tempBitmap);

并从代码中删除此行

imageView.draw(canvas);