In getRoundedCornerBitmap(Context context, Bitmap input, int pixels , int w , int h , boolean squareTL, boolean squareTR, boolean squareBL, boolean squareBR ) method below i attempted to display rounded image but when i try to add a border around the circle nothing is displayed. How can i add border to this rounded method.
public static Bitmap getRoundedCornerBitmap(Context context, Bitmap input, int pixels , int w , int h , boolean squareTL, boolean squareTR, boolean squareBL, boolean squareBR ) {
Bitmap output = Bitmap.createBitmap(w, h, Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final float densityMultiplier = context.getResources().getDisplayMetrics().density;
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, w, h);
final RectF rectF = new RectF(rect);
//make sure that our rounded corner is scaled appropriately
final float roundPx = pixels*densityMultiplier;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
//draw rectangles over the corners we want to be square
if (squareTL ){
canvas.drawRect(0, 0, w/2, h/2, paint);
}
if (squareTR ){
canvas.drawRect(w/2, 0, w, h/2, paint);
}
if (squareBL ){
canvas.drawRect(0, h/2, w/2, h, paint);
}
if (squareBR ){
canvas.drawRect(w/2, h/2, w, h, paint);
}
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(input, 0,0, paint);
return output;
}
Update now the circle is cut from left and bottom. How can i get a full rounded image
Try below code :-
int w = bitmap.getWidth();
int h = bitmap.getHeight();
int radius = Math.min(h / 2, w / 2);
Bitmap output = Bitmap.createBitmap(w + 8, h + 8, Config.ARGB_8888);
Paint p = new Paint();
p.setAntiAlias(true);
Canvas c = new Canvas(output);
c.drawARGB(0, 0, 0, 0);
p.setStyle(Style.FILL);
c.drawCircle((w / 2) + 4, (h / 2) + 4, radius, p);
p.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
c.drawBitmap(bitmap, 4, 4, p);
p.setXfermode(null);
p.setStyle(Style.STROKE);
p.setColor(Color.WHITE);
p.setStrokeWidth(3);
c.drawCircle((w / 2) + 4, (h / 2) + 4, radius, p);
return output;
see below link for more info:-
How to add a shadow and a border on circular imageView android?
Adding a round frame circle on rounded bitmap
or use below code :-
imageViewUser.setImageBitmap(new GraphicsUtil().getCircleBitmap(GraphicsUtil.decodeSampledBitmapFromResource(filePath,120, 120))); // filepath is your image path
GraphicsUtil.java
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
public class GraphicsUtil
{
/*
* Draw image in circular shape Note: change the pixel size if you want
* image small or large
*/
public Bitmap getCircleBitmap(Bitmap bitmap)
{
Bitmap output;
Canvas canvas = null;
final int color = 0xffff0000;
final Paint paint = new Paint();
Rect rect = null;
if (bitmap.getHeight() > 501)
{
output = Bitmap.createBitmap(500, 500, Bitmap.Config.ARGB_8888);
canvas = new Canvas(output);
rect = new Rect(0, 0, 500, 500);
}
else
{
//System.out.println("output else =======");
bitmap = Bitmap.createScaledBitmap(bitmap, 500, 500, false);
output = Bitmap.createBitmap(500, 500, Bitmap.Config.ARGB_8888);
canvas = new Canvas(output);
rect = new Rect(0, 0, 500, 500);
}
final RectF rectF = new RectF(rect);
paint.setAntiAlias(true);
paint.setDither(true);
paint.setFilterBitmap(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawOval(rectF, paint);
paint.setColor(Color.BLUE);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth((float) 1);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight)
{
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth)
{
// Calculate ratios of height and width to requested height and
// width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will
// guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromResource(String path, int reqWidth, int reqHeight)
{
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
}
Related
I need to change an image, from circle to normal square.
I'm a beginner a few weeks in programming,
I'm 2 days stopped in this code, does anyone know how to change?
I already tried everything, but I could not solve
I do not understand anything about canvas, I've already studied to solve this problem, but I'm still not able to
public static Bitmap getCircleBitmap(Bitmap bitmap) {
final int scaledWidth = 100;
final int scaledHeight = 100;
bitmap = Bitmap.createScaledBitmap(bitmap, scaledWidth, scaledHeight, true);
Bitmap output;
Rect srcRect, dstRect;
float r;
final int width = bitmap.getWidth();
final int height = bitmap.getHeight();
if (width > height) {
output = Bitmap.createBitmap(height, height, Bitmap.Config.ARGB_8888);
int left = (width - height) / 2;
int right = left + height;
srcRect = new Rect(left, 0, right, height);
dstRect = new Rect(0, 0, height, height);
r = height / 2;
} else {
output = Bitmap.createBitmap(width, width, Bitmap.Config.ARGB_8888);
int top = (height - width) / 2;
int bottom = top + width;
srcRect = new Rect(0, top, width, bottom);
dstRect = new Rect(0, 0, width, width);
r = width / 2;
}
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawCircle(r, r, r, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, srcRect, dstRect, paint);
bitmap.recycle();
return output;
}
public static Bitmap getBitmapFromVectorDrawable(Context context, int drawableId) {
Drawable drawable = AppCompatResources.getDrawable(context, drawableId);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
drawable = (DrawableCompat.wrap(drawable)).mutate();
}
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
}
If you look at your code, towards the end of method getCircleBitmap() you have the below line of code:
canvas.drawCircle(r, r, r, paint);
That's the one drawing the circle image for you using DrawCircle.
What you can do is, replace it with DrawRect. That should do that trick for you.
However, if you need to just draw a square image from a vector then you can use a standard ImageView straightaway and use the vector as image resource.
I tried To make imageview with rounded corners. But i am facing some issues. I cannot make the round corners for all 4 sides. I tried this code
Imageviewclass.class
Picasso.with(con).load(itemsArrayList.get(position).get("item_image")).transform(new Resizeimageview()).into(holder.img);
ResizeImageview.class
public class Resizeimageview implements Transformation {
#Override
public Bitmap transform(Bitmap source) {
int size = Math.min(source.getWidth(), source.getHeight());
int x = (source.getWidth() - size) / 2;
int y = (source.getHeight() - size) / 2;
Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size);
if (squaredBitmap != source) {
source.recycle();
}
Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig());
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
BitmapShader shader = new BitmapShader(squaredBitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
paint.setShader(shader);
paint.setAntiAlias(true);
float r = size / 8f;
canvas.drawRoundRect(new RectF(0, 0, source.getWidth(), source.getHeight()), r, r, paint);
squaredBitmap.recycle();
return bitmap;
}
#Override
public String key() {
return "rounded_corners";
}
}
Try replacing this line
canvas.drawRoundRect(new RectF(0, 0, source.getWidth(), source.getHeight()), r, r, paint);
with this
canvas.drawRoundRect(new RectF(0, 0, size, size), r, r, paint);
Try this :
Download the Universal Image Loader from the given link :
https://github.com/nostra13/Android-Universal-Image-Loader/wiki/Quick-Setup
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
context).build();
// Initialize ImageLoader with configuration.
ImageLoader.getInstance().init(config);
DisplayImageOptions options = new DisplayImageOptions.Builder().displayer(new RoundedBitmapDisplayer(250)).cacheOnDisc().build();
ImageLoader.getInstance().displayImage(itemsArrayList.get(position).get("item_image"), holder.img, options);
This question already has an answer here:
How to create a circular ImageView in Android? [duplicate]
(1 answer)
Closed 7 years ago.
I know there are a lot of examples on this question but l still couldn't finish following them, Is there an easy way how to make circle ImageView on android studio?
You not need to use any external libraries for make ImageView circle. Use this class for make your ImageView circle.
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
public class CircleImage {
Context context;
public RoundImage(Context context) {
this.context = context;
}
public Bitmap transform(Bitmap source) {
try {
int size = Math.min(source.getWidth(), source.getHeight());
int x = (source.getWidth() - size) / 2;
int y = (source.getHeight() - size) / 2;
Bitmap squaredBitmap = Bitmap
.createBitmap(source, x, y, size, size);
if (squaredBitmap != source) {
// source.recycle();
}
Bitmap bitmap = Bitmap.createBitmap(size, size,
squaredBitmap.getConfig());
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
BitmapShader shader = new BitmapShader(squaredBitmap,
BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
paint.setShader(shader);
paint.setAntiAlias(true);
float r = size / 2f;
canvas.drawCircle(r, r, r, paint);
// canvas.drawArc(rectf, -90, 360, false, lightRed);
// squaredBitmap.recycle();
return bitmap;
} catch (Exception e) {
// TODO: handle exception
}
return BitmapFactory.decodeResource(context.getResources(),
R.drawable.ic_launcher);
}
}
And use your ImageView in Java file
your_imageview.setImageBitmap(new RoundImage(
getApplicationContext()).transform(your_image_bitmap));
You can use external libraries Circle Image View
Use below code to make Bitmap to Circle Bitmap for ImageView :
public static Bitmap getRoundedRectBitmap(Bitmap bitmap, int pixels) {
Bitmap result = null;
try {
result = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(result);
int color = 0xff424242;
Paint paint = new Paint();
Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
int w = bitmap.getWidth();
int h = bitmap.getHeight();
int pl = 1;
int pr = 1;
int pt = 1;
int pb = 1;
int usableWidth = w - (pl + pr);
int usableHeight = h - (pt + pb);
int radius = Math.min(usableWidth, usableHeight) / 2;
int cx = pl + (usableWidth / 2);
int cy = pt + (usableHeight / 2);
canvas.drawCircle(cx, cy, radius, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
} catch (NullPointerException e) {
} catch (OutOfMemoryError o) {
}
return result;
}
I need to create shadow effect for an image .
private static Bitmap getDropShadow3(Bitmap bitmap) {
if (bitmap==null) return null;
int think = 6;
int w = bitmap.getWidth();
int h = bitmap.getHeight();
int newW = w - (think);
int newH = h - (think);
Bitmap.Config conf = Bitmap.Config.ARGB_8888;
Bitmap bmp = Bitmap.createBitmap(w, h, conf);
Bitmap sbmp = Bitmap.createScaledBitmap(bitmap, newW, newH, false);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
Canvas c = new Canvas(bmp);
// Right
Shader rshader = new LinearGradient(newW, 0, w, 0, Color.GRAY, Color.LTGRAY, Shader.TileMode.CLAMP);
paint.setShader(rshader);
c.drawRect(newW, think, w, newH, paint);
// Bottom
Shader bshader = new LinearGradient(0, newH, 0, h, Color.GRAY, Color.LTGRAY, Shader.TileMode.CLAMP);
paint.setShader(bshader);
c.drawRect(think, newH, newW , h, paint);
//Corner
Shader cchader = new LinearGradient(0, newH, 0, h, Color.LTGRAY, Color.LTGRAY, Shader.TileMode.CLAMP);
paint.setShader(cchader);
c.drawRect(newW, newH, w , h, paint);
c.drawBitmap(sbmp, 0, 0, null);
return bmp;
}
i used the above code, and i get two sides (Right, bottom) shadow effect . How can i make the effect in all sides including (top,Left)?
the method that you are using; may cause some problems with a certain type of images (irregular ones)
try this method instead (much much easier to understand and more flexible):
public Bitmap addShadowToBitmap(final Bitmap bm, final int dstHeight, final int dstWidth, int color, int size, float dx, float dy) {
final Bitmap mask = Bitmap.createBitmap(dstWidth, dstHeight, Config.ALPHA_8);
final Matrix scaleToFit = new Matrix();
final RectF src = new RectF(0, 0, bm.getWidth(), bm.getHeight());
final RectF dst = new RectF(0, 0, dstWidth - dx, dstHeight - dy);
scaleToFit.setRectToRect(src, dst, ScaleToFit.CENTER);
final Matrix dropShadow = new Matrix(scaleToFit);
dropShadow.postTranslate(dx, dy);
final Canvas maskCanvas = new Canvas(mask);
final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
maskCanvas.drawBitmap(bm, scaleToFit, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_OUT));
maskCanvas.drawBitmap(bm, dropShadow, paint);
final BlurMaskFilter filter = new BlurMaskFilter(size, Blur.NORMAL);
paint.reset();
paint.setAntiAlias(true);
paint.setColor(color);
paint.setMaskFilter(filter);
paint.setFilterBitmap(true);
final Bitmap ret = Bitmap.createBitmap(dstWidth, dstHeight, Config.ARGB_8888);
final Canvas retCanvas = new Canvas(ret);
retCanvas.drawBitmap(mask, 0, 0, paint);
retCanvas.drawBitmap(bm, scaleToFit, null);
mask.recycle();
return ret;
}
call it through:
addShadowToBitmap(arg0, arg1, arg2, arg3, arg4, arg5, arg6);
and it will return you a bitmap.
hope this will help.
Ahmad's code was not quite right for me. I augmented his code to determine w/h of returned bitmap based on the dx/dy and shadow size. This code worked for me with a bitmap that was a signature of a user.
public Bitmap addShadowToBitmap(final Bitmap bm, int color, int size, int dx, int dy) {
int dstWidth = bm.getWidth() + dx + size/2;
int dstHeight = bm.getHeight() + dy + size/2;
final Bitmap mask = Bitmap.createBitmap(dstWidth, dstHeight, Bitmap.Config.ALPHA_8);
final Canvas maskCanvas = new Canvas(mask);
final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
maskCanvas.drawBitmap(bm, 0, 0, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OUT));
maskCanvas.drawBitmap(bm, dx, dy, paint);
final BlurMaskFilter filter = new BlurMaskFilter(size, BlurMaskFilter.Blur.NORMAL);
paint.reset();
paint.setAntiAlias(true);
paint.setColor(color);
paint.setMaskFilter(filter);
paint.setFilterBitmap(true);
final Bitmap ret = Bitmap.createBitmap(dstWidth, dstHeight, Bitmap.Config.ARGB_8888);
final Canvas retCanvas = new Canvas(ret);
retCanvas.drawBitmap(mask, 0, 0, paint);
retCanvas.drawBitmap(bm, 0, 0, null);
mask.recycle();
return ret;
}
I want to scale a Bitmap using Canvas
I need to keep the Bitmap original width and height
and the scaled one aligns center-middle in bound
here is what I have tried:
public Bitmap scale(Bitmap src) {
int width = src.getWidth();
int height = src.getHeight();
float scaledWidth = width * .5f;
float scaledHeight = height * .5f;
Bitmap transBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(transBitmap);
Paint paint = new Paint();
float dx = (width - scaledWidth);
float dy = (height - scaledHeight);
canvas.drawBitmap(src, null, new RectF(dx, dy, scaledWidth, scaledHeight), paint);
Matrix m = new Matrix();
m.setRectToRect(new RectF(0, 0, src.getWidth(), src.getHeight()), new RectF(0, 0, scaledWidth, scaledHeight), Matrix.ScaleToFit.CENTER);
Bitmap output = Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), m, true);
//return transBitmap;
return output;
}
I used this method in custom ImageView onTouch:
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
setImageBitmap(scaledBmp);
break;
case MotionEvent.ACTION_UP:
setImageDrawable(originalDrawable);
break;
}
UPDATE
MyImageView.java
public class MyImageView extends ImageView {
private Drawable mDrawable;
private Drawable mScaled;
public MyImageView(Context context, Drawable drawable) {
super(context);
setImageDrawable(drawable);
Bitmap src = ((BitmapDrawable) drawable).getBitmap();
mDrawable = drawable;
mScaled = new BitmapDrawable(getResources(), makeScaled(src));
}
public Bitmap makeScaled(Bitmap src) {
int width = src.getWidth();
int height = src.getHeight();
float scaledWidth = width * .95f;
float scaledHeight = height * .95f;
Matrix m = new Matrix();
m.setRectToRect(new RectF(0, 0, src.getWidth(), src.getHeight()), new RectF(0, 0, scaledWidth, scaledHeight), Matrix.ScaleToFit.CENTER);
Bitmap output = Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), m, true);
Canvas xfas = new Canvas(output);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
xfas.drawBitmap(output, 0, 0, paint);
return output;
}
#Override public boolean dispatchTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
setImageDrawable(mScaled);
break;
case MotionEvent.ACTION_UP:
setImageDrawable(mDrawable);
break;
}
return super.dispatchTouchEvent(event);
}
}
If I have not misunderstood, one solution is to use a Matrix and its setRectToRect to translate the original values to the desired one. From the documentation
Set the matrix to the scale and translate values that map the source
rectangle to the destination rectangle, returning true if the the
result can be represented.
Matrix m = new Matrix();
m.setRectToRect(new RectF(0, 0, src.getWidth(), src.getHeight()), new RectF(0, 0, scaledWidth, scaledHeigth), Matrix.ScaleToFit.CENTER);
Bitmap output = Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), m, true);
and then simply draw the scaled bitmap on your canvas
Solved
public static Bitmap scaleBitmap(Bitmap src, float factor) {
int width = src.getWidth();
int height = src.getHeight();
int scaledWidth = (int) (width * factor);
int scaledHeight = (int) (height * factor);
Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Bitmap scaled = Bitmap.createScaledBitmap(src, scaledWidth, scaledHeight, false);
Canvas canvas = new Canvas(bmp);
Paint paint = new Paint();
int distX = (width - scaledWidth) / 2;
int distY = (height - scaledHeight) / 2;
canvas.drawBitmap(scaled, distX, distY, paint);
return bmp;
}