使用canvas android拉伸图像

时间:2013-04-03 09:53:29

标签: java android image bitmap android-canvas

您好我有两张图片,我正在使用画布合并图片

这是以下代码

      Intent intent = getIntent();

       //bm is the image get from camera
        bm = BitmapFactory.decodeFile(intent.getStringExtra("getdata"));

       //this is simple white text image
        bm1 = BitmapFactory.decodeResource(getResources(), R.drawable.txt_made_hawk_nelson);
        imgSeletedPhoto = (ImageView) findViewById(R.id.imgSelectedPhoto);

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

        int maxWidth = (width > bm1.getWidth() ? width : bm1.getWidth());
        int maxHeight = (height > bm1.getHeight() ? height : bm1.getHeight());


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

        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);          
    bmOverlay = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);

    Canvas canvas = new Canvas(bmOverlay);
    //canvas.drawBitmap(bm, 0, 0, null);
    canvas.drawBitmap(bm1, 0, 50, null);
    imgSeletedPhoto.setImageBitmap(bmOverlay);
    } catch (Exception e) {
        e.printStackTrace();
    }

我想缩放图像,图像应如下所示

enter image description here

但不是通过上面的代码,它看起来像

enter image description here

此文件的XML代码是

         <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:weightSum="10" >

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="0dp"
    android:layout_weight="7" >   // this is covering 70% of screen

    <ImageView
        android:id="@+id/imgSelectedPhoto"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_centerInParent="true" />
</RelativeLayout>

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="0dp"
    android:layout_weight="3"
    android:background="#baca9d"
    android:gravity="center"
    android:orientation="vertical"
    android:paddingLeft="10dp"
    android:paddingRight="10dp" >

任何身体都可以帮助我拉伸图像并从底部和顶部填充图像并将文本放在中心

1 个答案:

答案 0 :(得分:5)

int targetWidth  = 70% of screen width;
int targetHeight = 70% of screen height;

int saclex = (int)((float)targetWidth / (float)bmp1.getWidth());
int sacley = (int)((float)targetHeight / (float)bmp1.getHeight());

将缩放值应用于bmp1并创建缩放位图

saclex = (int)((float)targetWidth / (float)bmp.getWidth());
sacley = (int)((float)targetHeight / (float)bmp.getHeight());

应用比例值bmp并创建缩放位图。希望这会有所帮助。或者你可以使用这种方法来创建它。

Bitmap bitmap = Bitmap.createScaledBitmap(mTargetImage, bWidth,
                bHeight, false);