ImageView Scaling BOTTOM_CROP - android

I have two images that don't always completely fit onto the screen. Therefore I want to crop them (like CENTER_CROP does) but in a way, so that the bottom area of the image is always visible. Both images fill the entire screen width and each 1/2 of the screen height.
I found a similar solution here:
ImageView scaling TOP_CROP
The accepted solution works perfectly, but I can't figure out how to change the matrix to make it BOTTOM_CROP instead.
Working Code for TOP_CROP:
setScaleType(ScaleType.MATRIX);
Matrix matrix = getImageMatrix();
float scaleFactor = (getWidth() - Data.getImgPadding(c)) / (float) getDrawable().getIntrinsicWidth();
matrix.setScale(scaleFactor, scaleFactor, 0, 0);
setImageMatrix(matrix);
Note: A padding to the right is set programmatically, therefore it needs to be included in the calculation (the value is read by Data.getImgPadding(c)).
For BOTTOM_CROP I thought I'd use:
matrix.setScale(scaleFactor, scaleFactor, 0, getHeight());
But it's not really working, for the first image the bottom part is displayed more or less correctly, but there is some sort of margin below it - the bottom image border should be exactly at the bottom ImageView border. I assume I have to use the padding somehow but I don't know how to caculate the "new" image height after the horizontal padding value is set.
The bigger problem however is that (for whatever reason) when I set the value py in setScale() the second ImageView is suddenly empty... both views use the same layout xml, but that can't be the reason as the original code works perfectly on both.

I know this is a long time gone, but I've modified the answer in the post to suit your need.
#Override
protected boolean setFrame(int l, int t, int r, int b) {
boolean hasChanged = super.setFrame(l, t, r, b);
Matrix matrix = getImageMatrix();
float scaleFactor = getWidth() / (float) getDrawable().getIntrinsicWidth();
matrix.setScale(scaleFactor, scaleFactor, 0, 0);
// The Important Bit
Drawable drawable = getDrawable();
float heightD = drawable.getIntrinsicHeight();
float height = getHeight();
matrix.setTranslate(0, height - heightD);
setImageMatrix(matrix);
return hasChanged;
}
Hope it helps!

Related

Resizing an image to fit on a imageview

I am developing an application in which I need to fit an Bitmap into Imageview with specific dimensions(let's suppose 350dpx50dp - height*width).
I wanted to do something similar like this: http://gyazo.com/d739d03684e46411feb58d66acea1002
I have looked here for solutions. I found this code for scale the bitmap and fit it into imageview, but the problem is that imageview becomes greater when I add the bitmap into him:
private void scaleImage(Bitmap bitmap, ImageView view)
{
// Get current dimensions AND the desired bounding box
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int bounding = dpToPx(350);
// Determine how much to scale: the dimension requiring less scaling is
// closer to the its side. This way the image always stays inside your
// bounding box AND either x/y axis touches it.
float xScale = ((float) bounding) / width;
float yScale = ((float) bounding) / height;
float scale = (xScale <= yScale) ? xScale : yScale;
// Create a matrix for the scaling and add the scaling data
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
// Create a new bitmap and convert it to a format understood by the ImageView
Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
// Apply the scaled bitmap
view.setImageBitmap(scaledBitmap);
}
Using this code I can get this : http://gyazo.com/e9871db2130ac33668156fc0cf773594
But that's not what I wanted, I want to keep the dimensions of imageview and add the bitmap into imageview without modifying the dimensions of imageview and occupying all the imageview's surface. Like the first image.
Why don't you just add android:scaleType="fitXY" to your ImageView in xml?

how to crop a Bitmap so it matches the screen size

Starting point: in my app I let the user pick an image that will be used as the app's background. In case the image's width/height is larger than the device's screen width/height, I want to crop the image so it matches the device dimensions (see picture below).
I tried the method below, but with no luck at all, the resulting image is messed up.
private Bitmap crop(Bitmap bmp) {
int centerW = bmp.getWidth() / 2;
int centerH = bmp.getHeight() / 2;
int startX = centerW
//returns screen width
- GetSettings.getScreenDimensions(getActivity())[0] / 2;
int startY = centerH
//returns screen height
- GetSettings.getScreenDimensions(getActivity())[1] / 2;
return Bitmap.createBitmap(bmp, startX, startY,
GetSettings.getScreenDimensions(getActivity())[0],
GetSettings.getScreenDimensions(getActivity())[1]);
}
I guess I'm misunderstanding the parameters I need to pass to the createBitmap() method to get a proper result.
So how can I crop a Bitmap to make it's width/height to match the screen's width/height?
I'm not an android developer, but I would imagine your startX and startY variables are incorrect.
I would think you would want something like this:
startX = (bmp.getWidth() - screenWidth) / 2;
startY = (bmp.getHeight() - screenHeight) / 2;
Then your draw X and Y lengths would just be the screen width and height.

Scale bitmap from center point in Android for zoom in effect

I am trying to scale up a bitmap from its center point in Android to achieve a zoom effect, but without success. The code I have is:
float scaleWidth = ((float) width + (i * 5)) / width;
float scaleHeight = ((float) height + (i * 5)) / height;
Matrix matrix = new Matrix();
matrix.setScale(scaleWidth, scaleHeight, scaleWidth / 2, scaleHeight / 2);
Bitmap rescaledBitmap = Bitmap.createBitmap(src, 0, 0, width, height, matrix, true);
result.add(rescaledBitmap);
I am setting the pivot point by dividing the dimensions by 2, but the effect is just that the image is scaled from 0, 0 as coordinates instead of from the center. What I want is for the image to be a fixed size, but scaled up from its center point (thus cropping the image).
I'm going to offer an alternative solution using a property animator since that is a cleaner solution I think.
SomeLayout.xml (The key here is that the ViewGroup is the same size as the View, so it will clip as you requested (like google maps zoom in))
<FrameLayout
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center">
<View
android:id="#+id/zoom"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="#drawable/myCoolImage"
/>
</FrameLayout>
Code: (the 1,2,1 will start at a scale of 1x then 2x then back to 1x, it takes a list of values)
final View view = findViewById(R.id.zoom);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final ObjectAnimator animator = ObjectAnimator.ofFloat(view, View.SCALE_X, 1, 2, 1)
.ofFloat(view, View.SCALE_Y, 1, 2, 1)
.setDuration(5000);
animator.setInterpolator(new AccelerateDecelerateInterpolator());
animator.start();
}
});
So with this version image if you had a zoom +, and zoom - views with onClickListeners, you could basically simulate the controlled zooming as long as you know what values you want to zoom with.
Also as previously noted the ViewGroup being the same size as the internal view will force the animation to clip to it's parent bounds instead of being completely visible.
References:
Google Android ObjectAnimator
Sure this will come late, but for all looking after me:
double scaleFactor = 0.75; // Set this to the zoom factor
int widthOffset = (int) ((1 - scaleFactor)/2 * bmp.getWidth());
int heightOffset = (int) ((1 - scaleFactor)/2 * bmp.getHeight());
int numWidthPixels = bmp.getWidth() - 2 * widthOffset;
int numHeightPixels = bmp.getHeight() - 2 * heightOffset;
Bitmap rescaledBitmap = Bitmap.createBitmap(bmp, widthOffset, heightOffset, numWidthPixels, numHeightPixels, null, true);
This example will zoom in on the center of a bitmap and with a factor of 25%.
The second and third arguments in createBitmap take the x/y coordinates of the top left corner. You're sending 0,0, so if I understand correctly...
The image is correctly scaled, but the image is not centered, right?
To center it, you need to find the correct (x,y) point for the top left corner. This should be 1/4th the original width/height.
So...
Bitmap rescaledBitmap = Bitmap.createBitmap(src, (width/2), (height/2), width, height, matrix, true);
should work.

Define touchable area on a scaled image in android

I have asked questions related to this before, but I think I was framing my objective incorrectly.
What I have: a custom ImageView that displays a graphic and defines multiple touchable areas as rectangles within the image. My problem is scaling. I want to define the touchable area of the image based on it's actual resolution in the bitmap file, but translate those coordinates so the the rectangle covers the same area on the scaled image.
This is what I've got so far:
When the view is created, calculate the ratio of the actual to scaled sizes
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
Drawable pic=this.getDrawable();
int realHeight= pic.getIntrinsicHeight();
int realWidth=pic.getIntrinsicWidth();
int scaledHeight=this.getHeight();
int scaleWidth=this.getWidth();
heightRatio=(float)realHeight/scaledHeight;
widthRatio=(float)realWidth/scaleWidth;
}
Now I want to take the coordinates that define rectangle(s) on the original (un-scaled) image
and draw that rectangle(s) to the same area of the image -- but accounting for scale:
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint p=new Paint();
p.setStrokeWidth(1);
p.setColor(Color.BLUE);
for (HotSpot h: spots)
{
//Each hotspot has a rectangle defined in reference to the actual size of the image
Rect old=h.getRect();
float offsetLeft=old.left+(old.left*widthRatio);
float offsetTop=old.top+(old.top*heightRatio);
float offsetRight=old.right+(old.right*heightRatio);
float offsetBottom=old.bottom+(old.bottom*widthRatio);
RectF nRect=new RectF(offsetLeft,offsetTop,offsetRight,offsetBottom);
canvas.drawRect(nRect,p);
}
The results are "in the ball park" but not quite accurate. Any help is appreciated.
You can try this solution:
Get the screen density
Get the image height (or width)
Divide the height (or width) by the density, so you get the length in inches
Divide the coordinate by the length in inches, so you get a relationship between the coordinate and the image which is independent by the image effective size
When you have to draw the same point on a differently scaled image, multiply the last result for the length in inches of the second image (which you obtain using the same operations listed above)
Example:
On the first image:
float density = getResources().getDisplayMetrics().density;
int width = getWidth();
float inchesLength = width/density;
float scaledXCenter = xCenter / inchesLength;
On the same image with a different scale:
float density = getResources().getDisplayMetrics().density;
int width = getWidth();
float inchesLength = width/density;
float restoredXCenter = scaledXCenter * inchesLength;

ImageView bitmap scale dimensions

I have a Bitmap that is larger than the ImageView that I'm putting it in. I have the ScaleType set to center_inside. How do I get the dimensions of the scaled down image?
Ok. I probably should have been clearer. I needed the height and width of the scaled Bitmap before it's ever drawn to the screen so that I could draw some overlays in the correct position. I knew the position of the overlays in the original Bitmap but not the scaled. I figured out some simple formulas to calculate where they should go on the scaled Bitmap.
I'll explain what I did in case someone else may one day need this.
I got the original width and height of the Bitmap. The ImageView's height and width are hard-coded in the xml file at 335.
int bitmap_width = bmp.getWidth();
int bitmap_height = bmp.getHeight();
I determined which one was larger so that I could correctly figure out which one to base the calculations off of. For my current example, width is larger. Since the width was scaled down to the the width of the ImageView, I have to find the scaled down height. I just multiplied the ratio of the ImageView's width to the Bitmap's width times the Bitmap's height. Division is done last because Integer division first would have resulted in an answer of 0.
int scaled_height = image_view_width * bitmap_height / bitmap_width;
With the scaled height I can determine the amount of blank space on either side of the scaled Bitmap by using:
int blank_space_buffer = (image_view_height - scaled_height) / 2;
To determine the x and y coordinates of where the overlay should go on the scaled Bitmap I have to use the original coordinates and these calculated numbers. The x coordinate in this example is easy. Since the scaled width is the width of the ImageView, I just have to multiply the ratio of the ImageView's width to the Bitmap's width with the original x coordinate.
int new_x_coord = image_view_width * start_x / bitmap_width;
The y coordinate is a bit trickier. Take the ratio of the Bitmap's scaled height to the Bitmap's original height. Multiply that value with the original y coordinate. Then add the blank area buffer.
int new_y_coord = scaled_height * start_y / bitmap_height + blank_space_buffer;
This works for what I need. If the height is greater than the width, just reverse the width and height variables.
Here's how I do it:
ImageView iv = (ImageView)findViewById(R.id.imageview);
Rect bounds = iv.getDrawable().getBounds();
int scaledHeight = bounds.height();
int scaledWidth = bounds.width();
You can use Drawable's getIntrinsicWidth() or height method if you want to get the original size.
EDIT: Okay, if you're trying to access these bounds at the time onCreate runs, you'll have to wait and retrieve them till after the layout pass. While I don't know that this is the best way, this is how I've been able to accomplish it. Basically, add a listener to the ImageView, and get your dimensions just before it's drawn to the screen. If you need to make any layout changes from the dimensions you retrieve, you should do it within onPreDraw().
ImageView iv = (ImageView)findViewById(R.id.imageview);
int scaledHeight, scaledWidth;
iv.getViewTreeObserver().addOnPreDrawListener(
new ViewTreeObserver.OnPreDrawListener() {
#Override
public boolean onPreDraw() {
Rect rect = iv.getDrawable().getBounds();
scaledHeight = rect.height();
scaledWidth = rect.width();
iv.getViewTreeObserver().removeOnPreDrawListener(this);
return true;
}
});
Try this code:
final ImageView iv = (ImageView) findViewById(R.id.myImageView);
ViewTreeObserver vto = iv.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
Toast.makeText(MyActivity.this, iv.getWidth() + " x " + iv.getHeight(), Toast.LENGTH_LONG).show();
iv.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
});
Otherwise you can use onSizeChange() by making this view a custom one.

Categories

Resources