m using RecyclerView with StaggeredGrid (spanCount is variable). Each GridItem (a CardView) contains an a square ImageView. What i want is to load an Image from my backend with desired width and height to exactly fit an ImageView inside a CardView. Any suggestions i can achieve this? Code example is below:
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
Picasso.with(context)
.load(String.format("http://mybackend.com/image/w_%d,h_%d/%s",
holder.image.getMeasuredWidth(), // This returns 0, but i want here a real width
holder.image.getMeasuredWidth(),
myCollection.get(position).getImagePid()))
.tag(context)
.placeholder(R.drawable.placeholder_logo)
.into(holder.image);
In 2 words: somehow i need to get imageView dimensions (width) before my ViewHolder is bound.
Have you looked into using .fit() ? I believe that will resize the image to exactly fit an ImageView.
You can use ViewTreeObserver:
final int width = holder.image.getMeasuredWidth();
if (width > 0) {
Picasso.with(context)
.load(String.format("http://mybackend.com/image/w_%d,h_%d/%s",
holder.image.getMeasuredWidth(), // This returns 0, but i want here a real width
holder.image.getMeasuredWidth(),
myCollection.get(position).getImagePid()))
.tag(context)
.placeholder(R.drawable.placeholder_logo)
.into(holder.image);
} else {
holder.image.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
holder.image.getViewTreeObserver().removeGlobalOnLayoutListener(this);
Picasso.with(context)
.load(String.format("http://mybackend.com/image/w_%d,h_%d/%s",
holder.image.getMeasuredWidth(), // This returns 0, but i want here a real width
holder.image.getMeasuredWidth(),
myCollection.get(position).getImagePid()))
.tag(context)
.placeholder(R.drawable.placeholder_logo)
.into(holder.image);
}
});
}
Related
I am using PhotoView with Picasso and when I load images into ListView
1) It makes some images smaller.
2) not all images are loaded on launch, when i scroll down an then up then all the images are loaded.
Without PhotoView images loads just fine. I tried so many ImageView zooming libraries but PhotoView works better and I have also tried it with Glide the result is same.
Is there anyway I could force PhotoView to fit to ImageView attributes (which are Match_Parent)?
Here is my Adapter
#Override
public void onBindViewHolder( final ViewHolder holder, int position) {
Picasso.with(context)
.load((Integer) data.get(position))
.resize(530,999)
.onlyScaleDown()
.centerInside()
.into(holder.image);
holder.mAttacher = new PhotoViewAttacher(holder.image);
holder.image.setTag(holder);
}
#Override
public int getItemCount() {
return data.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public PhotoView image;
public PhotoViewAttacher mAttacher;
public ViewHolder(View view) {
super(view);
image = (PhotoView) view.findViewById(R.id.imagview);
I am loading images from resources/drawable not from any url
Unfortunately, there is an issue at Picasso, more details at issue #364
I switched to another library Glide
You can change your attacher scale type:
holder.mAttacher = new PhotoViewAttacher(holder.image);
holder.mAttacher.setScaleType(ImageView.ScaleType.CENTER_CROP);
CENTER_CROP: Scale the image uniformly (maintain the image's aspect ratio) so that
both dimensions (width and height) of the image will be equal to or
larger than the corresponding dimension of the view (minus padding).
The image is then centered in the view.
Im trying to find a way to measure an ImageView after an image has been loaded into it using Glide or Picasso (or anything really). Basically, im trying to layout other views on top of the image in certain positions, but need the final ImageViews dimensions to do so accurately.
Im not sure what the best layout to use to try and do this would be, but im currently using this:
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/viewingImageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</FrameLayout>
and loading the image into viewingImageView. These are both inside a root FrameLayout as well but I dont think that matters.
This is my latest attempt, but as commented, using .getWidth() and .getHeight() on the ImageView return 0. The width/height of the resource returns the size of the original image.
Glide
.with(this)
.load(entry.getImageUrl())
.asBitmap()
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
mImageView.setImageBitmap(resource);
int width = mImageView.getMaxWidth(); //prints 0
int height = mImageView.getMaxHeight(); //prints 0
int resw = resource.getWidth(); //returns original image width
}
});
So how can I get the image loaded and then measure the ImageView (or its wrapping FrameLayout) after the image has been loaded? Or if possible, measuring the dimensions of the finally laid out image would be better, as I know the image doesnt always fill the entire ImageView depending on scale types. I'm open to any solutions, the above is only what ive tried so far.
You should wait for the view to be drawn, you can use OnGlobalLayoutListener like this
ViewTreeObserver vto = mImageView.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
this.mImageView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
// Get the width and height
int width = mImageView.getMeasuredWidth();
int height = mImageView.getMeasuredHeight();
}
});
Create a custom class with image view.
Use this onMeasure in the image view we can get the height and width
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (mNeedsInitialScale) { // Set by setImage when a new image is set
// The measured width and height were set by super.onMeasure above
setInitialScale(getMeasuredWidth(), getMeasuredHeight());
mNeedsInitialScale = false;
}
}
I have a recycler view that has items with variable sizes. Now, I'm loading images using Picasso and I'd like to resize the pictures to fill the ImageView, preserving aspect ratio and by cropping the image so that it fits the ImageView perfectly. However, the width of the ImageView is 0 during the time the view holder is bound. How do I get the size?
The code looks something like this:
#Override
public void onBindViewHolder(ViewHolder holder, final int position)
{
Foo foo = mFoos.get(position);
// Get the size - THIS IS WHAT I WANT TO FIND OUT
int width = ...;
int height = 100;
// Load the image using Picasso
Picasso.with(mContext)
.load(foo.getImageURL())
.centerCrop()
.resize(width, height)
.into(holder.image);
}
That's because view measurement has not jet been made. So at that point width is actually 0.
You need to implement ViewTreeObserver
Take a look at some of these examples:
How to get the width and height of an Image View in android?
How to get the width and height of an android.widget.ImageView?
I'm using RecyclerView as horizontal list to show my images.
If I scroll to the fifth picture, the first two or three are recycled and ViewHolder loses its width. If I scroll back to the first image, the images are loaded again and that leads to jumps while scrolling.
Here is R.layout.fragment_details_view_img_item
<ImageView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/details_view_img_item"
android:background="#color/red"
android:adjustViewBounds="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</ImageView>
My ViewHolder and Adapter:
private class ViewHolder extends RecyclerView.ViewHolder {
ImageView img;
public ViewHolder(ImageView imgV){
super(imgV);
img = imgV;
}
}
private class ImageListAdapter extends RecyclerView.Adapter<ViewHolder> {
[...]
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int position) {
View v = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_details_view_img_item, parent, false);
v.setOnClickListener(listener);
logDebug("onCreateViewHolder");
return new ViewHolder((ImageView) v);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
logDebug("onBindViewHolder");
ImageItem item = data.get(i);
if (item != null) {
ImageView imgView = viewHolder.img;
imgView.setTag(item);
String imgurl = ImageUtil.imgUrlForAvailableHeightInPX(item, parentHeight);
ImageLoader.instance().loadASYNC(imgurl, imgView);
}
}
#Override
public void onViewRecycled(ViewHolder holder) {
super.onViewRecycled(holder);
logDebug("onViewRecycled: " + holder.img.getTag());
}
}
So how can I keep ViewHolder's width?
Before I start to approach this problem, one thing needs to be clear. The ViewHolder doesn't have any width, the ImageView it "holds" does have width, and that's what you're trying to control.
Now, considering this, your issue is (after making certain assumptions from looking at your code) that you need to know the width of a certain image when it is at a certain given height and while maintaining aspect ratio - before it arrives from the server.
This is a tricky one.
One option would be to preload all your images. This, however, is very costly with memory and could lead to memory crashes.
A better option would be to load all the images' details, without actually downloading the images' pixels. Then, you'll need to remember the aspect ratio of all the images in some cache, and set the dimension of the image you're loading prior to actually downloading the image contents.
To download an image's dimensions without downloading the image itself, you should use something like this:
public float getImageAspectRatio(InputStream inputStreamFromServer)
{
BitmapFactory.Options decodeOptions = new BitmapFactory.Options();
decodeOptions.inJustDecodeBounds = true;
BitmapFactory.decodeStream(inputStreamFromServer, null, decodeOptions);
final float imageDesiredWidth = decodeOptions.outWidth;
final float imageDesiredHeight = decodeOptions.outHeight;
return imageDesiredWidth / imageDesiredHeight;
}
Once you have this method, you'll need to preload all your images using this function:
private float[] mAspectRatios;
public void decodeAllAspectRatios(List<String> imageUrls)
{
mAspectRatios = new float[imageUrls.size()];
InputStream inputStream;
int index = 0;
for (String url : imageUrls)
{
// Get the input stream from the image url using whatever method you use.
mAspectRatios[index] = getImageAspectRatio(inputStream);
index++;
}
}
Important: Your RecyclerView should not begin working until this method finished working.
Once you have preloaded all your aspect ratios, we go back to your ViewHolder:
#Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
logDebug("onBindViewHolder");
ImageItem item = data.get(i);
if (item != null) {
ImageView imgView = viewHolder.img;
// set the layout params of the image, making it fit the correct size prior to loading the bitmap.
imgView.setLayoutParams(new LayoutParams(parentHeight * mAspectRatios[i], parentHeight));
imgView.setTag(item);
String imgurl = ImageUtil.imgUrlForAvailableHeightInPX(item, parentHeight);
ImageLoader.instance().loadASYNC(imgurl, imgView);
}
}
So long as you want your RecyclerView to display varying width images depending on their aspect ratio, I believe this is your best option.
I want to get the position of my ImageView programmatically. By position, I mean the distance in pixel from top of the screen to that ImageView. I have tried every other solution posted in stackoverflow but it's not working for me. My minimum API level is 8.
These are the codes I have tried-
ImageView image = (ImageView) findViewById(R.id.imageView1);
1) image.getTop();
2) private int getRelativeTop(View myView) {
if (myView.getParent() == myView.getRootView())
return myView.getTop();
else
return myView.getTop() + getRelativeTop((View) myView.getParent());
}
3) image.getLocationOnScreen(int[] locaiton);
You need to wait for the callback when the layout has been placed with children views. This is the listener you need to add to your root view in order to calculate the coordinates for your image. Otherwise it will return 0.
getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
public void onGlobalLayout() {
getViewTreeObserver().removeGlobalOnLayoutListener(this);
int[] locations = new int[2];
image.getLocationOnScreen(locations);
int x = locations[0];
int y = locations[1];
}
});
Use View.getLocationOnScreen() or getLocationInWindow() BUT ONLY after the view has been layout. getTop(), getLeft(), getBottom() and getRight() return the position relative to its parent.
Glide.with(this)
.asBitmap()
.apply(requestOptions)
.load(url)
.placeholder(R.mipmap.img_place_holder)
.apply(new RequestOptions().override(myImage.getMeasuredWidth(), myImage.getMeasuredHeight()))
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap bitmap,
Transition<? super Bitmap> transition) {
// TouchImageView myImage1 = findViewById(R.id.image_zoom_poll_card);
img_zoomIn.setVisibility(View.VISIBLE);
myImage.setImageBitmap(bitmap);
getBitmapPositionInsideImageView(myImage, img_zoomIn);
}
});