Android uses Glide to load network pictures and scale them equally
- 2021-10-11 19:40:40
- OfStack
When loading android pictures, due to the limited screen of mobile phones, when many large pictures are loaded, we require equal scaling, such as scaling the height according to a fixed width, so that the size ratio of the pictures can be scaled accordingly, but the pictures are not deformed. Obviously, it can't be implemented according to android: scaleType, because there will be many limitations, so you must write your own algorithm.
Scaling through Glide
In fact, glide provides such a method. Specifically, it shows the setResource method that inherits Transformation.
(1) Get the width and height of network or local pictures first
(2) Obtain the desired target width
(3) Obtain the height of the target in proportion
(4) Create a new map according to the width and height of the target
/**
* ===========================================
* Version Ben: 1.0
* Describe Description: Set the equal scale of the picture
* <p>glide Processing pictures .</p>
* ===========================================
*/
public class TransformationUtils extends ImageViewTarget<Bitmap> {
private ImageView target;
public TransformationUtils(ImageView target) {
super(target);
this.target = target;
}
@Override
protected void setResource(Bitmap resource) {
view.setImageBitmap(resource);
// Get the width and height of the original image
int width = resource.getWidth();
int height = resource.getHeight();
// Get imageView Width of
int imageViewWidth = target.getWidth();
// Calculate the scaling ratio
float sy = (float) (imageViewWidth * 0.1) / (float) (width * 0.1);
// Calculate the height of the picture after equal scale enlargement
int imageViewHeight = (int) (height * sy);
ViewGroup.LayoutParams params = target.getLayoutParams();
params.height = imageViewHeight;
target.setLayoutParams(params);
}
}
Then set transform in Glide
Glide.with(this)
.load(newActiviteLeftBannerUrl)
.asBitmap()
.placeholder(R.drawable.placeholder)
.into(new TransformationUtils(target));
Transformation This is a very powerful feature of Glide, which allows you to image in load- > In the middle of into ImageView, this pair of pictures is transformed in series 1. For example, if you want to do Gaussian blur, add rounded corners, do gray processing, round pictures, etc., you can do it through Transformation.
Summarize