Align an image to the bottom of an ImageView [duplicate] - android

I have an ImageView which is displaying a png that has a bigger aspect ratio than that of the device (vertically speaking - meaning its longer). I want to display this while maintaining aspect ratio, matching the width of the parent, and pinning the imageview to the top of the screen.
The problem i have with using CENTER_CROP as the scale type is that it will (understandable) center the scaled image instead of aligning the top edge to the top edge f the image view.
The problem with FIT_START is that the image will fit the screen height and not fill the width.
I have solved this problem by using a custom ImageView and overriding onDraw(Canvas) and handeling this manually using the canvas; the problem with this approach is that 1) I'm worried there may be a simpler solution, 2) I am getting a VM mem exception when calling super(AttributeSet) in the constructor when trying to set a src img of 330kb when the heap has 3 mb free (with a heap size of 6 mb) and cant work out why.
Any ideas / suggestions / solutions are much welcome :)
Thanks
p.s. i thought that a solution may be to use a matrix scale type and do it myself, but that seems to to be the same or more work than my current solution!

Ok, I have a working solution. The prompt from Darko made me look again at the ImageView class (thanks) and have applied the transformation using a Matrix (as i originally suspected but did not have success on my first attempt!). In my custom imageView class I call setScaleType(ScaleType.MATRIX) after super() in the constructor, and have the following method.
#Override
protected boolean setFrame(int l, int t, int r, int b)
{
Matrix matrix = getImageMatrix();
float scaleFactor = getWidth()/(float)getDrawable().getIntrinsicWidth();
matrix.setScale(scaleFactor, scaleFactor, 0, 0);
setImageMatrix(matrix);
return super.setFrame(l, t, r, b);
}
I have placed int in the setFrame() method as in ImageView the call to configureBounds() is within this method, which is where all the scaling and matrix stuff takes place, so seems logical to me (say if you disagree)
Below is the super.setFrame() method from the AOSP (Android Open Source Project)
#Override
protected boolean setFrame(int l, int t, int r, int b) {
boolean changed = super.setFrame(l, t, r, b);
mHaveFrame = true;
configureBounds();
return changed;
}
Find the full class src here

Here is my code for centering it at the bottom.
BTW in Dori's Code is a little bug: Since the super.frame() is called at the very end, the getWidth() method might return the wrong value.
If you want to center it at the top simply remove the postTranslate line and you're done.
The nice thing is that with this code you can move it anywhere you want. (right, center => no problem ;)
public class CenterBottomImageView extends ImageView {
public CenterBottomImageView(Context context) {
super(context);
setup();
}
public CenterBottomImageView(Context context, AttributeSet attrs) {
super(context, attrs);
setup();
}
public CenterBottomImageView(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
setup();
}
private void setup() {
setScaleType(ScaleType.MATRIX);
}
#Override
protected boolean setFrame(int frameLeft, int frameTop, int frameRight, int frameBottom) {
if (getDrawable() == null) {
return super.setFrame(frameLeft, frameTop, frameRight, frameBottom);
}
float frameWidth = frameRight - frameLeft;
float frameHeight = frameBottom - frameTop;
float originalImageWidth = (float)getDrawable().getIntrinsicWidth();
float originalImageHeight = (float)getDrawable().getIntrinsicHeight();
float usedScaleFactor = 1;
if((frameWidth > originalImageWidth) || (frameHeight > originalImageHeight)) {
// If frame is bigger than image
// => Crop it, keep aspect ratio and position it at the bottom and center horizontally
float fitHorizontallyScaleFactor = frameWidth/originalImageWidth;
float fitVerticallyScaleFactor = frameHeight/originalImageHeight;
usedScaleFactor = Math.max(fitHorizontallyScaleFactor, fitVerticallyScaleFactor);
}
float newImageWidth = originalImageWidth * usedScaleFactor;
float newImageHeight = originalImageHeight * usedScaleFactor;
Matrix matrix = getImageMatrix();
matrix.setScale(usedScaleFactor, usedScaleFactor, 0, 0); // Replaces the old matrix completly
//comment matrix.postTranslate if you want crop from TOP
matrix.postTranslate((frameWidth - newImageWidth) /2, frameHeight - newImageHeight);
setImageMatrix(matrix);
return super.setFrame(frameLeft, frameTop, frameRight, frameBottom);
}
}
Beginner tip: If it plain doesn't work, you likely have to extends androidx.appcompat.widget.AppCompatImageView rather than ImageView

You don't need to write a Custom Image View for getting the TOP_CROP functionality. You just need to modify the matrix of the ImageView.
Set the scaleType to matrix for the ImageView:
<ImageView
android:id="#+id/imageView"
android:contentDescription="Image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/image"
android:scaleType="matrix"/>
Set a custom matrix for the ImageView:
final ImageView imageView = (ImageView) findViewById(R.id.imageView);
final Matrix matrix = imageView.getImageMatrix();
final float imageWidth = imageView.getDrawable().getIntrinsicWidth();
final int screenWidth = getResources().getDisplayMetrics().widthPixels;
final float scaleRatio = screenWidth / imageWidth;
matrix.postScale(scaleRatio, scaleRatio);
imageView.setImageMatrix(matrix);
Doing this will give you the TOP_CROP functionality.

This example works with images that is loaded after creation of object + some optimization.
I added some comments in code that explain what's going on.
Remember to call:
imageView.setScaleType(ImageView.ScaleType.MATRIX);
or
android:scaleType="matrix"
Java source:
import com.appunite.imageview.OverlayImageView;
public class TopAlignedImageView extends ImageView {
private Matrix mMatrix;
private boolean mHasFrame;
#SuppressWarnings("UnusedDeclaration")
public TopAlignedImageView(Context context) {
this(context, null, 0);
}
#SuppressWarnings("UnusedDeclaration")
public TopAlignedImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
#SuppressWarnings("UnusedDeclaration")
public TopAlignedImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mHasFrame = false;
mMatrix = new Matrix();
// we have to use own matrix because:
// ImageView.setImageMatrix(Matrix matrix) will not call
// configureBounds(); invalidate(); because we will operate on ImageView object
}
#Override
protected boolean setFrame(int l, int t, int r, int b)
{
boolean changed = super.setFrame(l, t, r, b);
if (changed) {
mHasFrame = true;
// we do not want to call this method if nothing changed
setupScaleMatrix(r-l, b-t);
}
return changed;
}
private void setupScaleMatrix(int width, int height) {
if (!mHasFrame) {
// we have to ensure that we already have frame
// called and have width and height
return;
}
final Drawable drawable = getDrawable();
if (drawable == null) {
// we have to check if drawable is null because
// when not initialized at startup drawable we can
// rise NullPointerException
return;
}
Matrix matrix = mMatrix;
final int intrinsicWidth = drawable.getIntrinsicWidth();
final int intrinsicHeight = drawable.getIntrinsicHeight();
float factorWidth = width/(float) intrinsicWidth;
float factorHeight = height/(float) intrinsicHeight;
float factor = Math.max(factorHeight, factorWidth);
// there magic happen and can be adjusted to current
// needs
matrix.setTranslate(-intrinsicWidth/2.0f, 0);
matrix.postScale(factor, factor, 0, 0);
matrix.postTranslate(width/2.0f, 0);
setImageMatrix(matrix);
}
#Override
public void setImageDrawable(Drawable drawable) {
super.setImageDrawable(drawable);
// We have to recalculate image after chaning image
setupScaleMatrix(getWidth(), getHeight());
}
#Override
public void setImageResource(int resId) {
super.setImageResource(resId);
// We have to recalculate image after chaning image
setupScaleMatrix(getWidth(), getHeight());
}
#Override
public void setImageURI(Uri uri) {
super.setImageURI(uri);
// We have to recalculate image after chaning image
setupScaleMatrix(getWidth(), getHeight());
}
// We do not have to overide setImageBitmap because it calls
// setImageDrawable method
}

Based on Dori I'm using a solution which either scales the image based on the width or height of the image to always fill the surrounding container. This allows scaling an image to fill the whole available space using the top left point of the image rather than the center as origin (CENTER_CROP):
#Override
protected boolean setFrame(int l, int t, int r, int b)
{
Matrix matrix = getImageMatrix();
float scaleFactor, scaleFactorWidth, scaleFactorHeight;
scaleFactorWidth = (float)width/(float)getDrawable().getIntrinsicWidth();
scaleFactorHeight = (float)height/(float)getDrawable().getIntrinsicHeight();
if(scaleFactorHeight > scaleFactorWidth) {
scaleFactor = scaleFactorHeight;
} else {
scaleFactor = scaleFactorWidth;
}
matrix.setScale(scaleFactor, scaleFactor, 0, 0);
setImageMatrix(matrix);
return super.setFrame(l, t, r, b);
}
I hope this helps - works like a treat in my project.

None of these solutions worked for me, because I wanted a class that supported an arbitrary crop from either the horizontal or vertical direction, and I wanted it to allow me to change the crop dynamically. I also needed Picasso compatibility, and Picasso sets image drawables lazily.
My implementation is adapted directly from ImageView.java in the AOSP. To use it, declare like so in XML:
<com.yourapp.PercentageCropImageView
android:id="#+id/view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="matrix"/>
From source, if you wish to have a top crop, call:
imageView.setCropYCenterOffsetPct(0f);
If you wish to have a bottom crop, call:
imageView.setCropYCenterOffsetPct(1.0f);
If you wish to have a crop 1/3 of the way down, call:
imageView.setCropYCenterOffsetPct(0.33f);
Furthermore, if you elect to use another crop method, like fit_center, you may do so and none of this custom logic will be triggered. (Other implementations ONLY let you use their cropping methods).
Lastly, I added a method, redraw(), so if you elect to change your crop method/scaleType dynamically in code, you can force the view to redraw. For example:
fullsizeImageView.setScaleType(ScaleType.FIT_CENTER);
fullsizeImageView.redraw();
To go back to your custom top-center-third crop, call:
fullsizeImageView.setScaleType(ScaleType.MATRIX);
fullsizeImageView.redraw();
Here is the class:
/*
* Adapted from ImageView code at:
* http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.4.4_r1/android/widget/ImageView.java
*/
import android.content.Context;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
public class PercentageCropImageView extends ImageView{
private Float mCropYCenterOffsetPct;
private Float mCropXCenterOffsetPct;
public PercentageCropImageView(Context context) {
super(context);
}
public PercentageCropImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public PercentageCropImageView(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
public float getCropYCenterOffsetPct() {
return mCropYCenterOffsetPct;
}
public void setCropYCenterOffsetPct(float cropYCenterOffsetPct) {
if (cropYCenterOffsetPct > 1.0) {
throw new IllegalArgumentException("Value too large: Must be <= 1.0");
}
this.mCropYCenterOffsetPct = cropYCenterOffsetPct;
}
public float getCropXCenterOffsetPct() {
return mCropXCenterOffsetPct;
}
public void setCropXCenterOffsetPct(float cropXCenterOffsetPct) {
if (cropXCenterOffsetPct > 1.0) {
throw new IllegalArgumentException("Value too large: Must be <= 1.0");
}
this.mCropXCenterOffsetPct = cropXCenterOffsetPct;
}
private void myConfigureBounds() {
if (this.getScaleType() == ScaleType.MATRIX) {
/*
* Taken from Android's ImageView.java implementation:
*
* Excerpt from their source:
} else if (ScaleType.CENTER_CROP == mScaleType) {
mDrawMatrix = mMatrix;
float scale;
float dx = 0, dy = 0;
if (dwidth * vheight > vwidth * dheight) {
scale = (float) vheight / (float) dheight;
dx = (vwidth - dwidth * scale) * 0.5f;
} else {
scale = (float) vwidth / (float) dwidth;
dy = (vheight - dheight * scale) * 0.5f;
}
mDrawMatrix.setScale(scale, scale);
mDrawMatrix.postTranslate((int) (dx + 0.5f), (int) (dy + 0.5f));
}
*/
Drawable d = this.getDrawable();
if (d != null) {
int dwidth = d.getIntrinsicWidth();
int dheight = d.getIntrinsicHeight();
Matrix m = new Matrix();
int vwidth = getWidth() - this.getPaddingLeft() - this.getPaddingRight();
int vheight = getHeight() - this.getPaddingTop() - this.getPaddingBottom();
float scale;
float dx = 0, dy = 0;
if (dwidth * vheight > vwidth * dheight) {
float cropXCenterOffsetPct = mCropXCenterOffsetPct != null ?
mCropXCenterOffsetPct.floatValue() : 0.5f;
scale = (float) vheight / (float) dheight;
dx = (vwidth - dwidth * scale) * cropXCenterOffsetPct;
} else {
float cropYCenterOffsetPct = mCropYCenterOffsetPct != null ?
mCropYCenterOffsetPct.floatValue() : 0f;
scale = (float) vwidth / (float) dwidth;
dy = (vheight - dheight * scale) * cropYCenterOffsetPct;
}
m.setScale(scale, scale);
m.postTranslate((int) (dx + 0.5f), (int) (dy + 0.5f));
this.setImageMatrix(m);
}
}
}
// These 3 methods call configureBounds in ImageView.java class, which
// adjusts the matrix in a call to center_crop (android's built-in
// scaling and centering crop method). We also want to trigger
// in the same place, but using our own matrix, which is then set
// directly at line 588 of ImageView.java and then copied over
// as the draw matrix at line 942 of ImageVeiw.java
#Override
protected boolean setFrame(int l, int t, int r, int b) {
boolean changed = super.setFrame(l, t, r, b);
this.myConfigureBounds();
return changed;
}
#Override
public void setImageDrawable(Drawable d) {
super.setImageDrawable(d);
this.myConfigureBounds();
}
#Override
public void setImageResource(int resId) {
super.setImageResource(resId);
this.myConfigureBounds();
}
public void redraw() {
Drawable d = this.getDrawable();
if (d != null) {
// Force toggle to recalculate our bounds
this.setImageDrawable(null);
this.setImageDrawable(d);
}
}
}

Maybe go into the source code for the image view on android and see how it draws the center crop etc.. and maybe copy some of that code into your methods. i don't really know for a better solution than doing this. i have experience manually resizing and cropping the bitmap (search for bitmap transformations) which reduces its actual size but it still creates a bit of an overhead in the process.

public class ImageViewTopCrop extends ImageView {
public ImageViewTopCrop(Context context) {
super(context);
setScaleType(ScaleType.MATRIX);
}
public ImageViewTopCrop(Context context, AttributeSet attrs) {
super(context, attrs);
setScaleType(ScaleType.MATRIX);
}
public ImageViewTopCrop(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setScaleType(ScaleType.MATRIX);
}
#Override
protected boolean setFrame(int l, int t, int r, int b) {
computMatrix();
return super.setFrame(l, t, r, b);
}
#Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
computMatrix();
}
private void computMatrix() {
Matrix matrix = getImageMatrix();
float scaleFactor = getWidth() / (float) getDrawable().getIntrinsicWidth();
matrix.setScale(scaleFactor, scaleFactor, 0, 0);
setImageMatrix(matrix);
}
}

If you are using Fresco (SimpleDraweeView) you can easily do it with:
PointF focusPoint = new PointF(0.5f, 0f);
imageDraweeView.getHierarchy().setActualImageFocusPoint(focusPoint);
This one would be for a top crop.
More info at Reference Link

There are 2 problems with the solutions here:
They do not render in the Android Studio layout editor (so you can preview on various screen sizes and aspect ratios)
It only scales by width, so depending on the aspect ratios of the device and the image, you can end up with an empty strip on the bottom
This small modification fixes the problem (place code in onDraw, and check width and height scale factors):
#Override
protected void onDraw(Canvas canvas) {
Matrix matrix = getImageMatrix();
float scaleFactorWidth = getWidth() / (float) getDrawable().getIntrinsicWidth();
float scaleFactorHeight = getHeight() / (float) getDrawable().getIntrinsicHeight();
float scaleFactor = (scaleFactorWidth > scaleFactorHeight) ? scaleFactorWidth : scaleFactorHeight;
matrix.setScale(scaleFactor, scaleFactor, 0, 0);
setImageMatrix(matrix);
super.onDraw(canvas);
}

Simplest Solution: Clip the image
#Override
public void draw(Canvas canvas) {
if(getWidth() > 0){
int clipHeight = 250;
canvas.clipRect(0,clipHeight,getWidth(),getHeight());
}
super.draw(canvas);
}

Related

Android ImageView scale bitmap to the width and crop the height

I have a fixed size ImageView. I want to achieve this :
Scale the Bitmap always to the width, if the Bitmap is wider or smaller than Imageview width.
Crop the height if taller than ImageView height else scale it to the height.
I want something like this answer, but the other way around (FitXCropY). I have tried changing this answer with no success.
Thank you.
Based on this answer ImageView to scale to fixed height, but crop excess width
public class FitXCropYImageView extends ImageView {
boolean done = false;
#SuppressWarnings("UnusedDeclaration")
public FitXCropYImageView(Context context) {
super(context);
setScaleType(ScaleType.MATRIX);
}
#SuppressWarnings("UnusedDeclaration")
public FitYCropXImageView(Context context, AttributeSet attrs) {
super(context, attrs);
setScaleType(ScaleType.MATRIX);
}
#SuppressWarnings("UnusedDeclaration")
public FitXCropYImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setScaleType(ScaleType.MATRIX);
}
private final RectF drawableRect = new RectF(0, 0, 0,0);
private final RectF viewRect = new RectF(0, 0, 0,0);
private final Matrix m = new Matrix();
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (done) {
return;//Already fixed drawable scale
}
final Drawable d = getDrawable();
if (d == null) {
return;//No drawable to correct for
}
int viewHeight = getMeasuredHeight();
int viewWidth = getMeasuredWidth();
int drawableWidth = d.getIntrinsicWidth();
int drawableHeight = d.getIntrinsicHeight();
drawableRect.set(0, 0, drawableWidth, drawableHeight);//Represents the original image
//Compute the left and right bounds for the scaled image
float viewHalfHeight = viewHeight / 2;
float scale = (float) viewWidth / (float) drawableWidth;
float scaledHeight = drawableHeight * scale;
float scaledHalfHeight = scaledHeight / 2;
viewRect.set(0, viewHalfHeight-scaledHalfHeight,viewWidth, viewHalfHeight+scaledHalfHeight);
m.setRectToRect(drawableRect, viewRect, Matrix.ScaleToFit.CENTER /* This constant doesn't matter? */);
setImageMatrix(m);
done = true;
requestLayout();
}
}
Try like this,
Add inside Oncreate
viewImage = (ImageView) findViewById(R.id.pictureImageview123);
viewImage.setScaleType(ScaleType.FIT_XY);

How to draw an audio waveform on Android

I have a custom view that I want to use to display the amplitude of audio coming in through the microphone in a line graph.
Getting the amplitude and all that I have no problem with, and drawing the lines is not really a problem either.
What I want to do is show the amplitude starting at the far right edge, moving left. So with each new sample I want to translate the bitmap to the left, then draw a line from the last point to the new point. I'm not sure what the easiest way to achieve this is. I originally was able to do it by drawing Paths and just adding a new point to the path with each sample, the problem was that after like a minute the path was too big to be drawn. So I thought about it and wanted to switch to using a cached bitmap, translate that on each iteration, and draw from the last point to the new point. However this is tricky to do as (after experimentation). When I translate the bitmap it doesn't move the far left pixels off the bitmap, it just moves the entire bitmap in the canvas and I have no way to write pixels to the right side.
Below is a description of what I'm trying to do:
Given this:
I want to translate that to the left:
Then draw a line to a new point the space space on the right
Of course, step 2 and 3 should happen at essentially the same time.
How can I achieve this? I'm open to new ideas altogether, like perhaps saving all the points for up to 1 screen worth and drawing them out on each onDraw call. I'd prefer to just save them in a bitmap and do some kind of translation/clipping etc to achieve the same thing with perhaps less overhead.
private static final int MAX_AMPLITUDE = 32767;
float lx, ly;
private Paint mPaint;
private Bitmap mBitmap;
private Canvas mCanvas;
private void init() {
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(5);
mPaint.setColor(Color.Black);
}
#Override
public void onSizeChanged(int w, int h, int oldw, int oldh) {
if (mBitmap != null) {
mBitmap.recycle();
}
mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
height = h;
width = w;
ly = height;
lx = width;
amplitudeDivisor = ((float) MAX_AMPLITUDE / (float) height);
}
#Override
public void onDraw(Canvas canvas) {
mAmplitude = (float)(MAX_AMPLITUDE * Math.random());
float dx = width - delta;
float dy = height - (mAmplitude / amplitudeDivisor);
mCanvas.drawLine(lx, ly, dx, dy, mPaint);
mCanvas.translate(-delta, 0);
canvas.drawBitmap(mBitmap, 0, 0, mPaint);
lx = dx;
ly = dy;
delta+=10;
postInvalidateDelayed(200);
}
The above is just a sample, I'm just using a random value for the amplitude to simplify for now. I've tried a bunch of things with no luck. Any help would be greatly appreciated.
I ended up getting this working by saving the points to an array. I draw a white line before the recording starts. Note that I use an EvictingQueue from the Guava library as a circular buffer of points to render on a line. To use this, once a recording starts call start() and when it ends call stop. From your activity you will need to send MediaRecorder getMaxAmplitude() values to the updateAmplitude() method of this class, and do so at an interval of say 50 ms. The view also supports rotation.
public class AmplitudeWaveFormView extends View {
private static final String TAG = AmplitudeWaveFormView.class.getSimpleName();
private static final int MAX_AMPLITUDE = 32767;
private static final int SAMPLES_PER_SCREEN = 100;
private float mAmplitude = 0;
private Paint mRecordingPaint, mNotRecordingPaint;
private int height = -1;
private int width = -1;
private boolean mIsStarted;
private float[] lastPoints;
private int oldWidth = -1, oldHeight = -1;
private int mCurrentSample;
private float amplitudeDivisor = 1;
private float lx,ly, deltaX;
private EvictingQueue<Float> mPointQueue;
private int recordColor;
private int notRecordingColor;
public AmplitudeWaveFormView(Context context) {
super(context);
init();
}
public AmplitudeWaveFormView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public AmplitudeWaveFormView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public void start() {
mIsStarted = true;
}
public void stop() {
mIsStarted = false;
}
public void updateAmplitude(float amplitude) {
mAmplitude = amplitude;
postInvalidate();
}
private void init() {
recordColor = getResources().getColor(R.color.mint);
notRecordingColor = getResources().getColor(R.color.alpine);
mRecordingPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mRecordingPaint.setStyle(Paint.Style.STROKE);
mRecordingPaint.setStrokeWidth(5);
mRecordingPaint.setColor(recordColor);
mNotRecordingPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mNotRecordingPaint.setStyle(Paint.Style.STROKE);
mNotRecordingPaint.setStrokeWidth(5);
mNotRecordingPaint.setColor(notRecordingColor);
}
#Override
public void onSizeChanged(int w, int h, int oldw, int oldh) {
height = h;
width = w;
ly = height;
lx = width;
deltaX = (float)width / (float)SAMPLES_PER_SCREEN;
amplitudeDivisor = ((float) MAX_AMPLITUDE / (float) height);
mPointQueue = EvictingQueue.create(SAMPLES_PER_SCREEN * 4);
if (lastPoints != null && lastPoints.length > 0) {
float xScale = (float) width/oldWidth;
float yScale = (float) height/oldHeight;
Matrix matrix = new Matrix();
matrix.setScale(xScale, yScale);
matrix.mapPoints(lastPoints);
mPointQueue.addAll(Floats.asList(lastPoints));
ly = lastPoints[lastPoints.length-1];
lx= lastPoints[lastPoints.length -2];
lastPoints = null;
}
}
#Override
public void onRestoreInstanceState(Parcelable state) {
if (state instanceof Bundle) {
Bundle bundle = (Bundle) state;
mCurrentSample = bundle.getInt("sample");
lastPoints = bundle.getFloatArray("lines");
oldWidth = bundle.getInt("oldWidth");
oldHeight = bundle.getInt("oldHeight");
state = ((Bundle) state).getParcelable("parent");
}
super.onRestoreInstanceState(state);
}
#Override
public Parcelable onSaveInstanceState() {
Bundle bundle = new Bundle();
bundle.putFloatArray("lines", Floats.toArray(mPointQueue));
bundle.putInt("sample", mCurrentSample);
bundle.putParcelable("parent", super.onSaveInstanceState());
bundle.putInt("oldWidth", width);
bundle.putInt("oldHeight", height);
return bundle;
}
#Override
public void onDraw(Canvas canvas) {
if (mIsStarted) {
float x = lx + deltaX;
float y = height - (mAmplitude / amplitudeDivisor);
mPointQueue.add(lx);
mPointQueue.add(ly);
mPointQueue.add(x);
mPointQueue.add(y);
lastPoints = Floats.toArray(mPointQueue);
lx = x;
ly = y;
}
if (lastPoints != null && lastPoints.length > 0) {
int len = mPointQueue.size() / 4 >= SAMPLES_PER_SCREEN ? SAMPLES_PER_SCREEN * 4 : mPointQueue.size();
float translateX = width - lastPoints[lastPoints.length - 2];
canvas.translate(translateX, 0);
canvas.drawLines(lastPoints, 0, len, mRecordingPaint);
}
if (mCurrentSample <= SAMPLES_PER_SCREEN) {
drawNotRecordingLine(canvas);
}
mCurrentSample++;
}
private void drawNotRecordingLine(Canvas canvas) {
canvas.drawLine(0,height, width, height, mNotRecordingPaint);
}
}

Android: How to expand rectangular image with same ratio to fit the screen

I have the following rectangular image to be set in my application.
Now I am trying to expand the image with same ratio on both sides until it fits to the screen.But I cant get the expected image.
So far my code is :
<ImageView
android:id="#+id/imgid"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/shayneward"
android:scaleType="fitXY"/>
It dont care that the image gets cut off, but it should expand on both sides with same ratio until it fits to the screen.
Change android:scaleType="fitXY" to android:scaleType="centerCrop" to get the behavior that you want.
The different scaling options are documented under ImageView.ScaleType.
Try using this:
android:scaleType="centerCrop"
From the Android documentation, center crop does the following:
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).
See documentation for ImageView.ScaleType here.
if the image is too small could be a problem because it is not scaled to fit screen dimensions.
I use this class to solve this issue:
public class FixedCenterCrop extends ImageView {
public FixedCenterCrop(Context context) {
super(context);
setScaleType(ScaleType.MATRIX);
}
public FixedCenterCrop(Context context, AttributeSet attrs) {
super(context, attrs);
setScaleType(ScaleType.MATRIX);
}
public FixedCenterCrop(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setScaleType(ScaleType.MATRIX);
}
#Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
recomputeImgMatrix();
}
#Override
protected boolean setFrame(int l, int t, int r, int b) {
recomputeImgMatrix();
return super.setFrame(l, t, r, b);
}
private void recomputeImgMatrix() {
final Matrix matrix = getImageMatrix();
float scale;
final int viewWidth = getWidth() - getPaddingLeft() - getPaddingRight();
final int viewHeight = getHeight() - getPaddingTop() - getPaddingBottom();
final int drawableWidth = getDrawable().getIntrinsicWidth();
final int drawableHeight = getDrawable().getIntrinsicHeight();
if (drawableWidth * viewHeight > drawableHeight * viewWidth) {
scale = (float) viewHeight / (float) drawableHeight;
} else {
scale = (float) viewWidth / (float) drawableWidth;
}
matrix.setScale(scale, scale);
matrix.postTranslate((viewWidth - drawableWidth * scale) / 2, (viewHeight - drawableHeight*scale)/2);
setImageMatrix(matrix);
}
}

Scale text over image in custom imageview

I have written a custom imageview to show a credit card. To create the credit card I have a base image and I have setters to set the PAN, Card holder, expiry. This text needs to be drawn on top of the base card image. My problem is maintaining the position and size of the text so that it will always look correct no matter the changing size of the base image. The only thing I can rely on is the aspect ratio of the image being the same as a normal credit card.
My custom ImageView
public class CardView extends ImageView {
private String mPan = "4321 0123 4567 8910";
private String mExpiry = "01/16";
private String mCardholder = "MR JOHN SMITH";
private float mPanTextSize = 22;
private float mOtherTextSize = 14;
private Paint mPanPaint = new Paint();
private Paint mCardholderPaint = new Paint();
public CardView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initCardView();
}
public CardView(Context context, AttributeSet attrs) {
super(context, attrs);
initCardView();
}
public CardView(Context context) {
super(context);
initCardView();
}
private final void initCardView() {
mPanPaint.setColor(0xFFFFFFFF);
mPanPaint.setShadowLayer(1, 1, 1, 0xAA000000);
mPanPaint.setAntiAlias(true);
mPanPaint.setTextSize(mPanTextSize * getResources().getDisplayMetrics().scaledDensity);
mPanPaint.setTypeface(Typeface.MONOSPACE);
mCardholderPaint.setColor(0xFFFFFFFF);
mCardholderPaint.setShadowLayer(1, 1, 1, 0xAA000000);
mCardholderPaint.setAntiAlias(true);
mCardholderPaint.setTextSize(mOtherTextSize * getResources().getDisplayMetrics().scaledDensity);
mCardholderPaint.setTypeface(Typeface.MONOSPACE);
setPadding(0,0,0,0);
//setAdjustViewBounds(true);
setScaleType(ImageView.ScaleType.CENTER_INSIDE);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
float panLength = mPanPaint.measureText(mPan);
float x = (getWidth() - panLength)/2;
float y = -mPanPaint.ascent() + (getHeight() * 0.46f);
canvas.drawText(mPan, x, y, mPanPaint);
x = (getWidth() - panLength)/1.5f;
y = y - mCardholderPaint.ascent();
canvas.drawText(mExpiry, x, y, mCardholderPaint);
y = y - mCardholderPaint.ascent();
canvas.drawText(mCardholder, x, y, mCardholderPaint);
//super.onDraw(canvas);
}
public void setPan(String pan) {
mPan = pan;
invalidate();
}
public String getPan() {
return mPan;
}
public void setExpiry(String expiry) {
mExpiry = expiry;
invalidate();
}
public String getExpiry() {
return mExpiry;
}
public void setCardholder(String cardholder) {
mCardholder = cardholder;
invalidate();
}
public String getCardholder() {
return mCardholder;
}
}
So sometimes this looks ok but as you get to 10 inch screens the text is way too small, right in the center of the image (imagine looking at a credit card but the number only takes up the space of the middle 8 digits), and as you get to small screens the text is too big, going right up to the image sides or past them.
Any solutions? Any explanation why?
You need to make the text sizes dependent on the size of your image.
try to experiment with different values for yourPanFactor and yourCardholderFactor until you get the desired result
#Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (changed) {
final int height = bottom-top;
mPanPaint.setTextSize(height*yourPanFactor);
mCardholderPaint.setTextSize(height*yourCardholderFactor);
}
}
I managed to make this work in this lines of code
if (imageView.getWidth() <= resource.getWidth()) {
ratio = (float) resource.getWidth() / (float) imageView.getWidth();
} else {
ratio = (float) imageView.getWidth() / (float) resource.getWidth();
}
Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setTextSize(editText.getTextSize() * ratio);
Note that the editText has the default text size which is 14 sp.
I hope it help you. and correct me if am wrong

android Gallery with arbitrary aspect ratios

i wish to have an android gallery that will host images of varying aspect ratios. what i'd like is something like CENTER_CROP for the images in the gallery. however, when i set the image scale type to this, the images overrun the gallery image border.
of course, FIT_XY results in squished / flattened images. CENTER results in horizontal or vertical black space inside the gallery image border.
any ideas how to accomplish this? every example i can find uses FIT_XY with fixed size images. i suppose i could crop the images myself but i'd rather not.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView iv = (ImageView) convertView;
if (iv == null) {
iv = new ImageView(context);
iv.setScaleType(ImageView.ScaleType.FIT_XY);
iv.setBackgroundResource(galleryItemBackground);
iv.setLayoutParams(new Gallery.LayoutParams(200, 200));
}
InputStream is;
try {
is = getInputStream(position);
} catch (IOException ioe) {
// TODO?
throw new RuntimeException(ioe);
}
Bitmap bm = BitmapFactory.decodeStream(is);
iv.setImageBitmap(bm);
/*
* if (bitmaps[position] != null) { bitmaps[position].recycle();
* bitmaps[position] = null; } bitmaps[position] = bm;
*/
return iv;
}
I had the same problem as you and looking at ScaleType documentation I found it could be done using ScaleType.MATRIX, for example:
int w = 1000;
int h = 1000;
Paint p = new Paint();
p.setShader(new LinearGradient(0, 0, w, h, Color.BLACK, Color.RED, Shader.TileMode.CLAMP));
Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas g = new Canvas(bmp);
g.drawRect(new Rect(0, 0, w, h), p);
ImageView i3 = new ImageView(context);
i3.setImageBitmap(bmp);
i3.setScaleType(ScaleType.MATRIX);
int viewWidth = 300;
int viewHeight = 300;
Matrix matrix = new Matrix();
matrix.postScale(bmp.getWidth() / viewWidth, bmp.getHeight() / viewHeight, bmp.getWidth() / 2, bmp.getHeight() / 2);
i3.setImageMatrix(matrix);
LayoutParams lp2 = new LayoutParams(viewWidth, viewHeight);
lp2.leftMargin = 100;
lp2.topMargin = 400;
lp2.gravity = 0;
this.addView(i3, lp2);
This solution complicates things a little bit too much though. If you want to scroll and zoom the ImageView you need to use matrix scaling as well. So I'd be interested in knowing any possible alternative.
For this kind of tasks I use this simple class. It fits height or width scaling the image properly (it depends on which is the smaller dimension) . After this operation it centers the image in the ImageView bounds.
public class FixedCenterCrop extends ImageView {
public FixedCenterCrop(Context context) {
super(context);
setScaleType(ScaleType.MATRIX);
}
public FixedCenterCrop(Context context, AttributeSet attrs) {
super(context, attrs);
setScaleType(ScaleType.MATRIX);
}
public FixedCenterCrop(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setScaleType(ScaleType.MATRIX);
}
#Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
recomputeImgMatrix();
}
#Override
protected boolean setFrame(int l, int t, int r, int b) {
recomputeImgMatrix();
return super.setFrame(l, t, r, b);
}
private void recomputeImgMatrix() {
final Matrix matrix = getImageMatrix();
float scale;
final int viewWidth = getWidth() - getPaddingLeft() - getPaddingRight();
final int viewHeight = getHeight() - getPaddingTop() - getPaddingBottom();
final int drawableWidth = getDrawable().getIntrinsicWidth();
final int drawableHeight = getDrawable().getIntrinsicHeight();
if (drawableWidth * viewHeight > drawableHeight * viewWidth) {
scale = (float) viewHeight / (float) drawableHeight;
} else {
scale = (float) viewWidth / (float) drawableWidth;
}
matrix.setScale(scale, scale);
matrix.postTranslate((viewWidth - drawableWidth * scale) / 2, (viewHeight - drawableHeight*scale)/2);
setImageMatrix(matrix);
}
}
I ended up just trimming the bitmap to a square myself, as,
Bitmap bm = BitmapFactory.decodeStream(is);
// make it square
int w = bm.getWidth();
int h = bm.getHeight();
if (w > h) {
// trim width
bm = Bitmap.createBitmap(bm, (w - h) / 2, 0, h, h);
} else {
bm = Bitmap.createBitmap(bm, 0, (h - w) / 2, w, w);
}

Categories

Resources