convert drawable xml containing a gradient to bitmap - android

I want to apply a gradient to a bitmap. So far I'm using this technique.
here is my code in the onCreate method of MainActivity.class.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
double angle = Math.toRadians(135);
double length = 100;
int x = (int) (Math.cos(angle) * length);
int y = (int) (Math.sin(angle) * length);
int[] colors = new int[3];
colors[0] = Color.parseColor("#FF4081");
colors[1] = Color.parseColor("#3F51B5");
Bitmap bitmap = Bitmap.createBitmap(1080, 1080, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
LinearGradient linearGradient =
new LinearGradient(0, 0, x, y, colors[1], colors[0], Shader.TileMode.CLAMP);
Paint paint = new Paint();
paint.setDither(true);
paint.setShader(linearGradient);
canvas.drawRect(new RectF(0, 0, 1080, 1080), paint);
ImageView imageView = findViewById(R.id.iv);
imageView.setImageBitmap(bitmap);
}
}
which results in this
but I want to get an effect like this
image 2 results were achieved by simply creating a drawable XML file with the following code
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:angle="45"
android:endColor="#color/colorPrimary"
android:startColor="#color/colorAccent" />
</shape>
and setting it as a background for an ImageView, but I want this effect on the bitmap because I want to save that bitmap locally as an Image. I have tried creating a GradientDrawable instance in the MainActivity and calling onDraw(canvas) on the GradientDrawable as mentioned in the post

As I see, you calculated the angle incorrect.
Instead of this
LinearGradient linearGradient =
new LinearGradient(0, 0, x, y, colors[1], colors[0], Shader.TileMode.CLAMP);
Use this
LinearGradient linearGradient =
new LinearGradient(1080, 0, 0, 1080, colors[1], colors[0], Shader.TileMode.CLAMP);
x0 is gradient start X, y0 is gradient start Y, x1 is gradient end X and y1 is gradient end Y.
Hope I helped you.

Related

How to create a partially-rounded-corners-rectangular drawable with center-crop and without creating new bitmap?

Background
I've already seen how to create a drawable that's circular out of a bitmap, and also how to add an outline (AKA stroke) around it, here.
The problem
I can't find out how to do a similar task for rounding only some of the corners of the bitmap, inside the drawable, without creating a new bitmap, and still do it for a center-crop ImageView.
What I've found
This is what I've found, but it does create a new bitmap, and when using it in an imageView with center-crop (source here):
/**
* Create rounded corner bitmap from original bitmap.
*
* #param input Original bitmap.
* #param cornerRadius Corner radius in pixel.
* #param squareTL,squareTR,squareBL,squareBR where to use square corners instead of rounded ones.
*/
public static Bitmap getRoundedCornerBitmap(final Bitmap input, final float cornerRadius, final int w, final int h,
final boolean squareTL, final boolean squareTR, final boolean squareBL, final boolean squareBR) {
final Bitmap output = Bitmap.createBitmap(w, h, Config.ARGB_8888);
final Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Rect rect = new Rect(0, 0, w, h);
final RectF rectF = new RectF(rect);
// make sure that our rounded corner is scaled appropriately
Paint paint = new Paint();
paint.setXfermode(null);
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, cornerRadius, cornerRadius, 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(PORTER_DUFF_XFERMODE_SRC_IN);
canvas.drawBitmap(input, 0, 0, paint);
return output;
}
And, this is what I've found for creating a rounded corners drawable that acts on all corners:
public static class RoundedCornersDrawable extends Drawable {
private final float mCornerRadius;
private final RectF mRect = new RectF();
private final BitmapShader mBitmapShader;
private final Paint mPaint;
public RoundedCornersDrawable(final Bitmap bitmap, final float cornerRadius) {
mCornerRadius = cornerRadius;
mBitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP,
Shader.TileMode.CLAMP);
mPaint = new Paint();
mPaint.setAntiAlias(false);
mPaint.setShader(mBitmapShader);
mRect.set(0, 0, bitmap.getWidth(), bitmap.getHeight());
}
#Override
protected void onBoundsChange(final Rect bounds) {
super.onBoundsChange(bounds);
mRect.set(0, 0, bounds.width(), bounds.height());
}
#Override
public void draw(final Canvas canvas) {
canvas.drawRoundRect(mRect, mCornerRadius, mCornerRadius, mPaint);
}
#Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
#Override
public void setAlpha(final int alpha) {
mPaint.setAlpha(alpha);
}
#Override
public void setColorFilter(final ColorFilter cf) {
mPaint.setColorFilter(cf);
}
}
But this solution only works well if the imageView shows the content while maintaining the same aspect ratio as the bitmap, and also has its size pre-determined.
The question
How to create a center-cropped drawable, that shows a bitmap, has rounded corners for specific corners, and also be able to show an outline/stroke around it?
I want to do it without creating a new bitmap or extending ImageView. Only use a drawable that has the bitmap as the input.
The SMART way is to use the PorterDuff blending mode. It's really simple and slick to create any fancy shading, blending, "crop" effect. you can find a lot of good tutorial about PorterDuff. here a good one.
I always use this library to achieve what you are looking for. you can round any corner you want and also add stroke.
https://github.com/vinc3m1/RoundedImageView
You can use it or see it's source codes just for inspiration.
EDIT
there is no need to use Image View and make bitmap or drawable yourself and show it in Image View.
Just replace Image View with Rounded Image View and it will handle everything for you without any extra work in code !
here is sample :
<com.makeramen.roundedimageview.RoundedImageView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/imageView1"
android:scaleType="centerCrop"
app:riv_corner_radius="8dp"
app:riv_border_width="2dp"
app:riv_border_color="#333333"
app:riv_oval="false" />
In code, just pass any image resource to it or use any Image Loader with it.
RoundedImageView myRoundedImage=(RoundedImageView)findViewById(R.id.imageView1);
myRoundedImage.setImageResource(R.drawable.MY_DRAWABLE);
// OR
ImageLoader.getInstance().displayImage(YOUR_IMAGE_URL, myRoundedImage);
if you want to just make specific corners rounded try this:
<com.makeramen.roundedimageview.RoundedImageView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/imageView1"
android:scaleType="centerCrop"
app:riv_corner_radius_top_right="8dp"
app:riv_corner_radius_bottom_right="8dp"
app:riv_border_width="2dp"
app:riv_border_color="#333333"
app:riv_oval="false" />
Well, you can create a new .xml drawable named my_background and paste this code below:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
>
<solid android:color="#00000000"/>
<corners
android:bottomLeftRadius="12dp"
android:bottomRightRadius="12dp"
android:topLeftRadius="12dp"
android:topRightRadius="12dp" />
<stroke
android:width="1dp"
android:color="#000000"
/>
</shape>
Then, you set your ImageButton's, ImageView's background to your new drawable, like this:
android:background="#drawable/my_background"
android:scaleType="centerCrop"
or programatically:
myView.setBackground(R.drawable.my_background);
Hope it helps!
EDIT:
To programmatically create a similar drawable, you can use it:
GradientDrawable shape = new GradientDrawable();
shape.setShape(GradientDrawable.RECTANGLE);
shape.setCornerRadii(new float[] { 8, 8, 8, 8, 0, 0, 0, 0 });
shape.setColor(Color.TRANSPARENT);
shape.setStroke(3, Color.BLACK);
v.setBackgroundDrawable(shape);
Ok, here's my try. The only gotcha is that "int corners" is meant to be a set of flags. Such as 0b1111 where each 1 represents a corner to be rounded, and 0 is the opposite. The order is TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT.
example usage first, formatted for readability:
((ImageView) findViewById(R.id.imageView)).setImageDrawable(
new RoundedRectDrawable(
getResources(),
bitmap,
(float) .15,
0b1101,
8,
Color.YELLOW
)
);
code:
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.os.SystemClock;
/**
* Created by mliu on 4/15/16.
*/
public class RoundedRectDrawable extends BitmapDrawable {
private final BitmapShader bitmapShader;
private final Paint p;
private final RectF rect;
private final float borderRadius;
private final float outlineBorderRadius;
private final int w;
private final int h;
private final int corners;
private final int border;
private final int bordercolor;
public RoundedRectDrawable(final Resources resources, final Bitmap bitmap, float borderRadiusSeed, int corners, int borderPX, int borderColor) {
super(resources, bitmap);
bitmapShader = new BitmapShader(getBitmap(),
BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
final Bitmap b = getBitmap();
p = getPaint();
p.setAntiAlias(true);
p.setShader(bitmapShader);
w = b.getWidth();
h = b.getHeight();
rect = new RectF(0,0,w,h);
borderRadius = borderRadiusSeed * Math.min(w, h);
border = borderPX;
this.corners = corners;
this.bordercolor = borderColor;
outlineBorderRadius = borderRadiusSeed * Math.min(w+border,h+border);
}
#Override
public void draw(final Canvas canvas) {
if ((corners&0b1111)==0){
if (border>0) {
Paint border = new Paint();
border.setColor(bordercolor);
canvas.drawRect(rect, border);
}
canvas.drawRect(rect.left + border, rect.top + border, rect.width() - border, rect.height() - border, p);
} else {
if (border >0) {
Paint border = new Paint();
border.setColor(bordercolor);
canvas.drawRoundRect(rect, outlineBorderRadius, outlineBorderRadius, border);
if ((corners & 0b1000) == 0) {
//top left
canvas.drawRect(rect.left, rect.top, rect.width() / 2, rect.height() / 2, border);
}
if ((corners & 0b0100) == 0) {
//top right
canvas.drawRect(rect.width() / 2, rect.top, rect.width(), rect.height() / 2, border);
}
if ((corners & 0b0010) == 0) {
//bottom left
canvas.drawRect(rect.left, rect.height() / 2, rect.width() / 2, rect.height(), border);
}
if ((corners & 0b0001) == 0) {
//bottom right
canvas.drawRect(rect.width() / 2, rect.height() / 2, rect.width(), rect.height(), border);
}
}
canvas.drawRoundRect(new RectF(rect.left + border, rect.top + border, rect.width() - border, rect.height() - border), borderRadius, borderRadius, p);
if ((corners & 0b1000) == 0) {
//top left
canvas.drawRect(rect.left + border, rect.top + border, rect.width() / 2, rect.height() / 2, p);
}
if ((corners & 0b0100) == 0) {
//top right
canvas.drawRect(rect.width() / 2, rect.top + border, rect.width() - border, rect.height() / 2, p);
}
if ((corners & 0b0010) == 0) {
//bottom left
canvas.drawRect(rect.left + border, rect.height() / 2, rect.width() / 2, rect.height() - border, p);
}
if ((corners & 0b0001) == 0) {
//bottom right
canvas.drawRect(rect.width() / 2, rect.height() / 2, rect.width() - border, rect.height() - border, p);
}
}
}
}
So, this handles the outline first, if needed, then the bitmap. It marks the canvas up with a rounded rect first, then "squares out" each corner you don't want to round. Seems highly inefficient, and probably is, but average case run time before minimal optimizations (corners = 0b0000, 10 canvas.draw calls) takes ~ 200us on a S7. And, that time is SUPER inconsistent based on phone usage. I've gotten as low as 80us and as high as 1.5ms.
NOTES/WARNING: I am BAD at this. This is not optimal. There's probably better answers already here on SO. The subject matter is just a bit uncommon and difficult to search up. I was originally not going to post this, but at time of writing this is still not marked answered, and the library OP did not wish to use due to problems with their Drawable actually use a very similar approach as my terrible solution. So, now I'm less embarrassed to share this. Additionally, though what I posted today was 95% written yesterday, I know I got some of this code from a tutorial or a SO post, but I can't remember who to attribute cause I didn't end up using it in my project. Apologies whoever you are.

Rounded top corners of bitmap android

I am using this code to get top rounded corners of bitmap
public static void setTopRounded(Bitmap workingBitmap , int w, int h, ImageView v,Context context)
{
Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bmp);
Shader shader = new BitmapShader(workingBitmap, Shader.TileMode.MIRROR,
Shader.TileMode.MIRROR);
Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG);
paint.setAntiAlias(true);
paint.setShader(shader);
RectF rec = new RectF(0, 0, w, h - 20);
c.drawRect(new RectF(0, 20, w, h), paint);
c.drawRoundRect(rec, 10, 10, paint);
v.setBackgroundDrawable(new BitmapDrawable(context.getResources(), bmp));
}
and my XML code for Image view is
<ImageView
android:layout_height="140dp"
android:layout_width="match_parent"
android:id="#+id/profileIV"
android:visibility="gone"
android:scaleType="centerCrop" />
now the problem is by setting
v.setBackgroundDrawable(new BitmapDrawable(context.getResources(), bmp)),
android:scaleType="centerCrop"
property did not work and if i use
v.setImageDrawable(new BitmapDrawable(context.getResources(), bmp))
then scale type works but the image does not get rounded.
What i am doing wrong?
Try v.setImageBitmap(bmp) instead
/**
* This method used for bitmap compress and rounded corner
* #param Bitmap object
* #param pixels
* #return nothing
*/
public static Bitmap getRoundedRectBitmap(final Bitmap bitmap,final int pixels)
{
int color;
float roundPx;
final Bitmap result = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(result);
color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
roundPx = pixels;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return result;
}
//call the above method like this
profileImage.setImageBitmap(getRoundedRectBitmap(bitmap, 50));
I found the answer. I did not change any thing. Using the same function for top rounded corners image and use bitmap as background in image view. But now doing CenterCrop in code for imageView using ThumbnailUtils
First i use below function to get scaled CenterCroped image
Bitmap resizedProfileBitmap = ThumbnailUtils.extractThumbnail(profileBitmap, voucherTitleRLT.getWidth(), height);
and then use top rounded function to get set top rounded center croped image as background of imageview like below
setTopRounded(resizedProfileBitmap, resizedProfileBitmap.getWidth(), resizedProfileBitmap.getHeight(), profileIV, thisContext);
You can do this in XML by creating a Shape Drawable and setting it as the background on your ImageView. This article explains how: http://www.techrepublic.com/article/pro-tip-round-corners-on-an-android-imageview-with-this-hack/#
Your shape drawable can look like this:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#00ffffff" />
<padding
android:left="1dp"
android:top="1dp"
android:right="1dp"
android:bottom="1dp" />
<corners
android:topLeftRadius="6dp"
android:topRightRadius="6dp"
android:bottomLeftRadius="0.1dp"
android:bottomRightRadius="0.1dp" />
<stroke
android:width="6dp"
android:color="#ffffffff" />

Android view background colored with transparent element

We can easily make a background transparent & colored element with Shape like this :
Color bleue : Solid color
white/gray square : transparent
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<corners
android:radius="20dp"/>
<solid
android:color="#1f93ed" />
</shape>
But how can i do a view background with colored back and transparent element like this :
as if the background color was holed by form...
Any idea?
You can draw yourself colored area with override of onDraw in custom drawable or view.
For exemple, in this code i draw four "corner outline" :
#Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
drawCorner(cornerSizeInPixel, canvas, Color.GREEN));
}
private void drawCorner(int size, Canvas canvas, int color)
{
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(color);
paint.setStyle(Style.FILL);
// top left
Path p = new Path();
p.moveTo(0, 0);
p.lineTo(size, 0);
p.arcTo(new RectF(0, 0, size, size), 180, 90, true);
p.lineTo(0, 0);
canvas.drawPath(p, paint);
// bottom left
int h = canvas.getHeight();
p = new Path();
p.moveTo(0, h);
p.lineTo(size, h);
p.arcTo(new RectF(0, h - size, size, h), 90, 90, true);
p.lineTo(0, h);
canvas.drawPath(p, paint);
// top right
int w = canvas.getWidth();
p = new Path();
p.moveTo(w, 0);
p.lineTo(w - size, 0);
p.arcTo(new RectF(w - size, 0, w, size), 270, 90, true);
p.lineTo(w, 0);
canvas.drawPath(p, paint);
// bottom right
p = new Path();
p.moveTo(w, h);
p.lineTo(w - size, h);
p.arcTo(new RectF(w - size, h - size, w, h), 0, 90, true);
p.lineTo(w, h);
canvas.drawPath(p, paint);
}
Result: 4 green form in every corner of the image, which together draw a rounded rectangle really transparent
option 1: use normal .png file
option 2: create a custom Drawable by extending ShapeDrawable class
Replace android:color="#1f93ed" with android:color="#android:color/transparent and set the background to the Blue colour

create a image with color in android

Setting background doesn't seem to give any hint on size for android.
Hence I'm looking for a way to create an image with a specific color.
(would be better if could be done in xml)
in iOS this could be achieved by
+ (UIImage*)placeHolderImage
{
static UIImage* image = nil;
if(image != nil)
return image;
CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
// Seashell color
UIColor* color = [UIColor colorWithRed:255/255.0 green:245/255.0 blue:238/255.0 alpha:1.0];
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
Here is the equivalent Android code:
// CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
Rect rect = new Rect(0, 0, 1, 1);
//UIGraphicsBeginImageContext(rect.size);
//CGContextRef context = UIGraphicsGetCurrentContext();
Bitmap image = Bitmap.createBitmap(rect.width(), rect.height(), Config.ARGB_8888);
Canvas canvas = new Canvas(image);
//UIColor* color = [UIColor colorWithRed:255/255.0 green:245/255.0 blue:238/255.0 alpha:1.0];
int color = Color.argb(255, 255, 245, 238);
//CGContextSetFillColorWithColor(context, [color CGColor]);
Paint paint = new Paint();
paint.setColor(color);
//CGContextFillRect(context, rect);
canvas.drawRect(rect, paint);
//image = UIGraphicsGetImageFromCurrentImageContext();
//UIGraphicsEndImageContext();
/** nothing to do here, we already have our image **/
/** and the canvas will be released by the GC **/
Now, if you want to do this in XML its much easier:
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<size android:width="1px" android:height="1dp"/>
<solid android:color="#FFFFF5EE/>
</shape>
Although that won't give you a Bitmap, but a Drawable. It's just fine if you intend to just draw it somewhere. If you actually need a Bitmap, then you will have to use the above code to create a Canvas from a Bitmap and draw your Drawable into it.
This helps you in creating a bitmap image with a specific color.
firstly create a bitmap with name sampleBitmap like below
Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types
Bitmap sampleBitmap = Bitmap.createBitmap(300, 300, conf); // this creates a MUTABLE bitmap
next use the following code to get each pixel of the created bitmap
// int[] pixels = new int[sampleBitmap.getHeight()*sampleBitmap.getWidth()];
for (int i=0; i < sampleBitmap.getWidth(); i++)
{
for (int j=0; j < sampleBitmap.getHeight(); i++)
{
sampleBitmap.setPixel(i, j, Color.rgb(someColor1, someColor2, someColor3));
}
}
using this you can set the bitmap to the listview item so that the listitem doesnt collapse

Crop Image as circle in Android

Does anyone know how to crop an image\bitmap to a circle?
I can not find any solution, sorry ..
For having rounded corners for ImageView, convert your image into bitmap and then try following code :
private Bitmap getRoundedCroppedBitmap(Bitmap bitmap) {
int widthLight = bitmap.getWidth();
int heightLight = bitmap.getHeight();
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(),
Config.ARGB_8888);
Canvas canvas = new Canvas(output);
Paint paintColor = new Paint();
paintColor.setFlags(Paint.ANTI_ALIAS_FLAG);
RectF rectF = new RectF(new Rect(0, 0, widthLight, heightLight));
canvas.drawRoundRect(rectF, widthLight / 2, heightLight / 2, paintColor);
Paint paintImage = new Paint();
paintImage.setXfermode(new PorterDuffXfermode(Mode.SRC_ATOP));
canvas.drawBitmap(bitmap, 0, 0, paintImage);
return output;
}
Romain Guy, formerly an engineer on the Android team at Google, posted an excellent article on drawing images with rounded corners. This idea could be easily extended to a circle, for example, by changing the rounded rectangle radius so that it creates a complete circle.
From the article:
To generate the rounded images I simply wrote a custom Drawable that
draws a rounded rectangle using Canvas.drawRoundRect(). The trick is
to use a Paint with a BitmapShader to fill the rounded rectangle with
a texture instead of a simple color. Here is what the code looks like:
BitmapShader shader; shader = new BitmapShader(bitmap,
Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
Paint paint = new Paint(); paint.setAntiAlias(true);
paint.setShader(shader);
RectF rect = new RectF(0.0f, 0.0f, width, height);
// rect contains the bounds of the shape
// radius is the radius in pixels of the rounded corners
// paint contains the shader that will texture the shape
canvas.drawRoundRect(rect, radius, radius, paint);
Wiseman Designs, have an open source Circular ImageView ready for use
https://github.com/wisemandesigns/CircularImageView
This uses XML in your layouts, which makes life easier. You can set the source in XML or with some minor modification could easily use a Bitmap.
Disclaimer: I work for Wiseman Designs
Class:
public Bitmap getRoundedShape(Bitmap scaleBitmapImage) {
int targetWidth = 50;
int targetHeight = 50;
Bitmap targetBitmap = Bitmap.createBitmap(targetWidth,
targetHeight,Bitmap.Config.ARGB_8888);
canvas = new Canvas(targetBitmap);
Path path = new Path();
path.addCircle(((float) targetWidth - 1) / 2,
((float) targetHeight - 1) / 2,
(Math.min(((float) targetWidth),
((float) targetHeight)) / 2),
Path.Direction.CCW);
canvas.clipPath(path);
Bitmap sourceBitmap = scaleBitmapImage;
canvas.drawBitmap(sourceBitmap,
new Rect(0, 0, sourceBitmap.getWidth(),
sourceBitmap.getHeight()),
new Rect(0, 0, targetWidth,
targetHeight), null);
return targetBitmap;
}
View:
<ImageView
android:id="#+id/imgView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/btnEdit"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:background="#drawable/rounded"
android:adjustViewBounds="true"
android:gravity="center"
android:src="#drawable/happy"/>
Additional styles:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#android:color/white" />
<stroke
android:width="3dip"
android:color="#FF0000" />
<corners android:radius="10dp" />
<padding
android:bottom="0dp"
android:left="0dp"
android:right="0dp"
android:top="0dp" />
Try with below code :
public Bitmap getRoundedShape(Bitmap scaleBitmapImage) {
// TODO Auto-generated method stub
int targetWidth = 50;
int targetHeight = 50;
Bitmap targetBitmap = Bitmap.createBitmap(targetWidth,
targetHeight,Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(targetBitmap);
Path path = new Path();
path.addCircle(((float) targetWidth - 1) / 2,
((float) targetHeight - 1) / 2,
(Math.min(((float) targetWidth),
((float) targetHeight)) / 2),
Path.Direction.CCW);
canvas.clipPath(path);
Bitmap sourceBitmap = scaleBitmapImage;
canvas.drawBitmap(sourceBitmap,
new Rect(0, 0, sourceBitmap.getWidth(),
sourceBitmap.getHeight()),
new Rect(0, 0, targetWidth,
targetHeight), null);
return targetBitmap;
}
finalBitmapShader shader = newBitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mPaint.setShader(shader);
mBitmapWidth=mBitmap.getWidth();
mBitmapHeight=mBitmap.getHeight();
}
#Override
public void draw(Canvas canvas{
canvas.drawOval(mRectF,mPaint);
}
#Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
mRectF.set(bounds);
}
here I found a sample tutorial of it at
http://androidgreeve.blogspot.in/2014/09/facebook-messanger-like-profile-image.html?m=1

Categories

Resources