Bitmap of x cm's width and y cm's height

邮差的信 提交于 2019-12-11 16:42:04

问题


I am taking a picture using camera in my app and will email the picture to a certain email address. now i want the emailed picture's physical dimensions to be 10cm's in width and 8cm's in height. and the code i have tried is as follows:

1) declare a imageview in xml like below :

 <ImageView
    android:id="@+id/imageView3"
    android:layout_width="100mm"
    android:layout_height="80mm"
    android:src="@drawable/ic_launcher" />

2) and later in java file :

 final BitmapFactory.Options opts = new BitmapFactory.Options ();
    opts.inSampleSize = 2;
    final ImageView thumbNail = (ImageView)findViewById(R.id.imageView3);
    thumbNail.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {
            // TODO Auto-generated method stub
            thumbNail.setImageBitmap(Bitmap.createScaledBitmap (BitmapFactory.decodeFile(myPhoto.getPath(), opts), thumbNail.getWidth(), thumbNail.getHeight(), false));
        }
    });

As per the documentation the resulting bitmap should have width of 10cm's and height of 8cm's. but in xml file there is warning at these lines

    android:layout_width="100mm"
    android:layout_height="80mm"
     Avoid using "mm" as units (it does not work accurately on all devices); use "dp" instead.

so i don't have a clue as to what i should do. so please give me a solution that will work on all devices.


回答1:


This?

public static int mm2pixels(int val, Context current) {
    DisplayMetrics metrics = current.getResources().getDisplayMetrics();
    return (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_MM, val, metrics);
}



回答2:


i have used WarrenFaiths directions and came up with the below solution.

  DisplayMetrics metrics = activity.getResources().getDisplayMetrics();
  totalDIP_X = metrics.xdpi;
  totalDIP_Y = metrics.ydpi;

totalDIP_X and totalDIP_Y represent the total number of DIPs per inch on the phone.

so if you want the bitmap to be 5cms*5cms on phone, which is equivalent to 1.968inch*1.968inch, we should use the below code.

  imageView1.setImageBitmap(Bitmap.createScaledBitmap (aBitmap, (int)(1.968*totalDIP_X), (int)(1.968*totalDIP_Y), false));


来源:https://stackoverflow.com/questions/17450374/bitmap-of-x-cms-width-and-y-cms-height

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!