Android studio - Center non-transparent part of picture - java

I'm making an app that can freehand crop a picture using a canvas in android studio. My problem is that after cropping the picture, the cropped part stays in the same exact position as it was originally, whereas i want it to get centered and enlargened. Is there any way to take the non-transparent part and center it, or maybe remove the transparent part all-together?
Screenshot of my app where i want the banana to be centered
https://i.stack.imgur.com/8OKNT.png
Bitmap bitmap;
Path path = new Path();
Paint paint;
int width;
int height;
Rect src;
Rect dest;
public CutImage(Context context, Bitmap bitmap2) {
super(context);
bitmap = bitmap2;
paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setColor(Color.RED);
paint.setStrokeWidth(5f);
width = getWindowManager().getDefaultDisplay().getWidth();
height = getWindowManager().getDefaultDisplay().getHeight();
src = new Rect(0, 0, bitmap.getWidth() - 1, bitmap.getHeight() - 1);
dest = new Rect(0, 0, width - 1, height - 1);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.getHeight();
canvas.drawBitmap(bitmap,src,dest, null);
canvas.drawPath(path, paint);
}
private void crop() {
Bitmap croppedBitmap =
Bitmap.createBitmap(bitmap.getWidth(),bitmap.getHeight(),bitmap.getConfig());
Canvas cropCanvas = new Canvas(croppedBitmap);
Paint paint = new Paint();
cropCanvas.drawPath(path,paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
cropCanvas.drawBitmap(bitmap,src,dest,paint);
bitmap = croppedBitmap;
showImage2(bitmap);
}
} ```

Related

How to make images on Bitmap smaller?

I am trying to build a simple game on android and while setting the background image and other image assets on my main screen it is appearing too big as shown in the below image.
The actual size of the image is 1920x1080 and I want it to fit my screen like the image shown below:
The code for I have used is:
public class PoliceView extends View {
private Bitmap police;
private Bitmap background;
private Paint scorePaint = new Paint();
private Bitmap life[] = new Bitmap[2];
public PoliceView(Context context) {
super(context);
police = BitmapFactory.decodeResource(getResources(),R.drawable.police);
background = BitmapFactory.decodeResource(getResources(),R.drawable.gamebackground);
scorePaint.setColor(Color.BLACK);
scorePaint.setTextSize(70);
scorePaint.setTypeface(Typeface.DEFAULT_BOLD);
scorePaint.setAntiAlias(true);
life[0] = BitmapFactory.decodeResource(getResources(),R.drawable.heart);
life[1] = BitmapFactory.decodeResource(getResources(),R.drawable.brokenheart);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//The order of draw matters as objects are drawn in this same order
canvas.drawBitmap(background,0,0,null);
canvas.drawBitmap(police, 0, 0, null);
canvas.drawText("Score:",20, 60, scorePaint);
//Three lives for the police
canvas.drawBitmap(life[0],580, 10, null);
canvas.drawBitmap(life[0],680, 10, null);
canvas.drawBitmap(life[0],780, 10, null);
}}
How can I resize the images to fit the screen??
i use this code for resize image
Bitmap tmp = BitmapFactory.decodeFile(mPath);
ResizeWidth = (int) (your size);
ResizeHeight = (int) (your size);
Bitmap bitmap = Bitmap.createBitmap(ResizeWidth, ResizeHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Bitmap scaled = Bitmap.createScaledBitmap(tmp, ResizeWidth, ResizeHeight, true);
int leftOffset = 0;
int topOffset = 0;
canvas.drawBitmap(scaled, leftOffset, topOffset, null);
How to resize bitmap in canvas?
canvas.save(); // Save current canvas params (not only scale)
canvas.scale(scaleX, scaleY);
canvas.restore(); // Restore current canvas params
scale = 1.0f will draw the same visible size bitmap

Drawing a Bitmap to a Canvas with an alpha gradient

I'd like to draw a Bitmap on a Canvas, with a (linear) alpha gradient applied. The important point is that I don't want to overlay the image with any other color; the background (coming from the Views behind the View that I'd be drawing this Canvas to) should just "shine through". To illustrate, my goal would be something like this (the checkerboard pattern represents the View behind)
One would think that I could do something like this:
Bitmap bitmap = ...;
Paint paint = new Paint();
paint.setShader(new LinearGradient(0, 0, 100, 0, FROM, TO, Shader.TileMode.CLAMP));
canvas.drawBitmap(bitmap, 0, 0, paint);
but LinearGradient's FROM and TO arguments here would need to be colors, not alpha values; so there's no way that I see to specify that e.g. FROM should be fully transparent and TO should be fully opaque (without applying any color overlay).
use a ComposeShader, like this:
class V extends View {
Bitmap bitmap;
Paint paint = new Paint();
public V(Context context) {
super(context);
bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.chrome);
Shader shaderA = new LinearGradient(0, 0, bitmap.getWidth(), 0, 0xffffffff, 0x00ffffff, Shader.TileMode.CLAMP);
Shader shaderB = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
paint.setShader(new ComposeShader(shaderA, shaderB, PorterDuff.Mode.SRC_IN));
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawRect(0, 0, bitmap.getWidth(), bitmap.getHeight(), paint);
}
}
Based on this answer about masking, I was able to do this using a secondary off-screen canvas:
Bitmap backing = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
{
Canvas offscreen = new Canvas(backing);
offscreen.drawBitmap(bitmap, 0, 0, null);
Paint paint = new Paint();
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
paint.setShader(new LinearGradient(0, 0, 100, 0, 0x00000000, 0xFF000000, Shader.TileMode.CLAMP));
offscreen.drawRect(0, 0, bitmap.getWidth(), bitmap.getHeight(), paint);
}
canvas.drawBitmap(backing, 0, 0, null);

How can i make a dynamically created Bitmap to fit an ImageView?

I'd like to create a Bitmap from a String with a given text size and set it as source of an ImageView.
The ImageView in it's layout xml:
<ImageView
android:id="#+id/myImageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="fitXY"/>
Setting the Bitmap as src of the ImageView:
myImageView.setImageBitmap(getBitmapFromString("StringToDraw", 30));
My getBitmapFromString method:
private Bitmap getBitmapFromString(String string, float textSize) {
Bitmap bitmap = Bitmap.createBitmap(200, 200, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setSubpixelText(true);
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
paint.setTextSize(textSize);
paint.setTextAlign(Paint.Align.LEFT);
canvas.drawText(string, 0, 100, paint);
return bitmap;
}
How can i calculate the proper size for the Bitmap (from the given text size and String length) and how can i make it to fit the ImageView properly?
Found the solution in the following answer to a similar question:
https://stackoverflow.com/a/15252876/3363481
My code looks like this now:
private Bitmap getBitmapFromString(String text, float fontSizeSP, Context context) {
int fontSizePX = convertDiptoPix(context, fontSizeSP);
int pad = (fontSizePX / 9);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.WHITE);
paint.setTextSize(fontSizePX);
int textWidth = (int) (paint.measureText(text) + pad * 2);
int height = (int) (fontSizePX / 0.75);
Bitmap bitmap = Bitmap.createBitmap(textWidth, height, Bitmap.Config.ARGB_4444);
Canvas canvas = new Canvas(bitmap);
float xOriginal = pad;
canvas.drawText(text, xOriginal, fontSizePX, paint);
return bitmap;
}

How can I center this rectangle and image in the y axis?

So far, my image starts at 0,0 and scales properly. There is a black bar under it. How can I align it so that it is centered along the y, with a black bar above and below the image?
edit: also, what are "this.getWidth(), this.getHeight()" referring to when I make the object "dest" - the width of mBitmap? The documentation does say they represent the width of the view, I just want to make sure I'm correct in thinking that is it mBitmap.
public class SpotGameActivity extends Activity {
private Bitmap mBitmap;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.dpi2b);
setContentView(new BitMapView(this, mBitmap));
}
class BitMapView extends View {
Bitmap mBitmap = null;
public BitMapView(Context context, Bitmap bm) {
super(context);
mBitmap = bm;
}
#Override
protected void onDraw(Canvas canvas) {
//DisplayMetrics metrics = new DisplayMetrics();
//getWindowManager().getDefaultDisplay().getMetrics(metrics);
// called when view is drawn
Paint paint = new Paint();
paint.setFilterBitmap(true);
// The image will be scaled so it will fill the width, and the
// height will preserve the image’s aspect ration
float aspectRatio = ((float) mBitmap.getWidth()) / mBitmap.getHeight();
Rect dest = new Rect(0, 0, this.getWidth(),(int) (this.getWidth() / aspectRatio));
String AR = Double.toString(aspectRatio);
canvas.drawBitmap(mBitmap, null, dest, paint);
Toast.makeText(SpotGameActivity.this, AR, Toast.LENGTH_SHORT).show();
}
I've now gotten the difference between the view size and image size. I've divided the difference by 2 but now, my image is align to the bottom of the screen rather than the middle of the y-axis. any tips?:
#Override
protected void onDraw(Canvas canvas) {
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int scrHeight = this.getHeight();
String sH = Integer.toString(scrHeight);
Log.v(TAG, "scrHeight =" + sH );
int imgHeight= mBitmap.getHeight();
String iH = Integer.toString(imgHeight);
Log.v(TAG, "imgHeight =" + iH );
int diff = scrHeight - imgHeight;
String dif = Integer.toString(diff);
Log.v(TAG, "diff =" + dif );
int dvd= diff/2;
// called when view is drawn
Paint paint = new Paint();
paint.setFilterBitmap(true);
// The image will be scaled so it will fill the width, and the
// height will preserve the image’s aspect ration
float aspectRatio = ((float) mBitmap.getWidth()) / mBitmap.getHeight();
Rect dest = new Rect(0, dvd, this.getWidth(),(int) (this.getWidth() / aspectRatio)+dvd);
String AR = Double.toString(dvd);
canvas.drawBitmap(mBitmap, null, dest, paint);
Toast.makeText(SpotGameActivity.this, AR, Toast.LENGTH_SHORT).show();

Aspect ratio is off when scaling down and drawing a bitmap

The image I am using is from a 4x6. So the aspect ratio should be about .66. When I calculate the aspect ration in my code , I get around .66. However, the height of the displayed image looks squashed. The image only looks right if I set the aspect ratio manually to around .85.
Since setting the aspect ratio manually is not perfect, how can I get the can I keep the height of my image from appearing to be squashed.
public class SpotGameActivity extends Activity {
private Bitmap mBitmap;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.dpi2b);
setContentView(new BitMapView(this, mBitmap));
}
class BitMapView extends View {
Bitmap mBitmap = null;
public BitMapView(Context context, Bitmap bm) {
super(context);
mBitmap = bm;
}
#Override
protected void onDraw(Canvas canvas) {
// called when view is drawn
Paint paint = new Paint();
paint.setFilterBitmap(true);
// The image will be scaled so it will fill the width, and the
// height will preserve the image’s aspect ration
float aspectRatio = ((float) mBitmap.getWidth()) / mBitmap.getHeight();
Rect dest = new Rect(0, 0, this.getWidth(),(int) (this.getHeight() * aspectRatio));
String AR = Double.toString(aspectRatio);
//Rect dest = new Rect(0, 0, getWidth(), getHeight());
canvas.drawBitmap(mBitmap, null, dest, paint);
Toast.makeText(SpotGameActivity.this, AR, Toast.LENGTH_SHORT).show();
}
}
}
Aspect = width/height
newHeight = newWidth/Aspect
Do this,
Rect dest = new Rect(0, 0, this.getWidth(),(int) (this.getWidth() / aspectRatio));

Categories

Resources