In my application, I made an activity with CardView elements with pictures. The fact is that the pictures have a very large resolution. To load pictures into memory efficiently, I need to reduce their resolution to what CardView will have on some device. How do I know what size the program will have in CardView?
- where are these pictures from? Are they pre-placed on the device or downloaded from somewhere or how? - pavlofff
- @pavlofff they are in res / drawable - Maxgmer
- To solve your problem, there are so-called qualifiers. You place images of a suitable size in folders with appropriate qualifiers, for example, for the HDPI screen in the / drawable-hdpi / folder, the System itself will select the desired image. - pavlofff
- See this answer - pavlofff
- @pavlofff I want no qualifiers. The fact is that in my application in the future, the pictures will be uploaded by users. They will not be doing different pictures for different permissions and send them all. They will throw one high resolution image. - Maxgmer
2 answers
Get container size (px)
cardView.getMeasuredWidth() - width
cardView.getMeasuredHeight() - height
Upload a picture from the network:
Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream()); Change of size:
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) { int width = bm.getWidth(); int height = bm.getHeight(); float scaleWidth = ((float) newWidth) / width; float scaleHeight = ((float) newHeight) / height; Matrix matrix = new Matrix(); matrix.postScale(scaleWidth, scaleHeight); return Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false); } We use everything together after loading:
img_1.setImageBitmap(getResizedBitmap(bitmap, cardView.getMeasuredHeight(), cardView.getMeasuredWidth())); Most often, the server part has the ability to give a resource of an appropriate size and format, it makes sense to first make the correct request to get more suitable. It is desirable that the work on compression or decoding, took place in separate streams, well, it's up to you to decide. This is a simple example, without using lib.
- onethank you very much, very good, detailed answer) - Maxgmer
Found an interesting thing, I decided to answer right here, suddenly someone will come in handy.
- Universal Image Loader.
The bottom line is that UIL resizes the image exactly to the size of the image container. Here is the link https://github.com/nostra13/Android-Universal-Image-Loader