How to set vertical filled progress - android

I want to set the custom circular progress-bar like below:
EDITED
I wrote following code for this. But it is not work properly :
private void circularProgressBar(ImageView iv2, int i) {
Bitmap b = Bitmap.createBitmap(300, 300,Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(b);
Paint paint = new Paint();
paint.setColor(Color.parseColor("#c4c4c4"));
paint.setStrokeWidth(10);
paint.setStyle(Paint.Style.STROKE);
canvas.drawCircle(150, 150, 140, paint);
paint.setColor(Color.parseColor("#FFDB4C"));
paint.setStrokeWidth(10);
paint.setStyle(Paint.Style.FILL);
final RectF oval = new RectF();
paint.setStyle(Paint.Style.STROKE);
oval.set(10,10,290,290);
canvas.drawArc(oval, 270, ((i*360)/100), false, paint);
paint.setStrokeWidth(0);
// paint.setTextAlign(Align.CENTER);
paint.setColor(Color.parseColor("#8E8E93"));
// paint.setTextSize(140);
// canvas.drawText(""+i, 150, 150+(paint.getTextSize()/3), paint);
iv2.setImageBitmap(b);
}

Thanks Everyone for force me to do R&D and find out the solution...
Following code is the solution of the given question
XML
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/imagegreenid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="fitCenter"
android:src="#drawable/clip_full_green_gauge" />
<ImageView
android:id="#+id/imagewhiteid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/clip_feil_empty_gauge" />
</RelativeLayout>
Code in Activity:
int total_percent = orininalScore * 100;
int TOTAL_VALUE = 10000;
ImageView img = (ImageView) findViewById(R.id.imagegreenid);
ClipDrawable mImageDrawable = (ClipDrawable) img.getDrawable();
mImageDrawable.setLevel(total_percent);
ImageView img1 = (ImageView) findViewById(R.id.imagewhiteid);
ClipDrawable mImageDrawable1 = (ClipDrawable) img1.getDrawable();
mImageDrawable1.setLevel(TOTAL_VALUE - total_percent);

Related

Android - ImageView with rounded only one corner

I want to create ImageView like this (right side of the image):
I have it in CardView layout so I have rounded corners of the card but I need to create rounded left bottom corner of the image alone (or with top right).
I tried several options but nothing work correctly.
How can I do this? Do you have some tip?
You can use the Material Components Library.
With the version 1.2.0-alpha03 there is the new ShapeableImageView.
Just use in your layout:
<com.google.android.material.imageview.ShapeableImageView
app:srcCompat="#drawable/..."
../>
And in your code apply the ShapeAppearanceModel with:
float radius = getResources().getDimension(R.dimen.default_corner_radius);
imageView.setShapeAppearanceModel(imageView.getShapeAppearanceModel()
.toBuilder()
.setTopRightCorner(CornerFamily.ROUNDED,radius)
.setBottomLeftCorner(CornerFamily.ROUNDED,radius)
.build());
You can use this library and put your ImageView inside the Layout
https://github.com/JcMinarro/RoundKornerLayouts
and can set the radius for specific corners like this
containerLayout.setCornerRadius(2f, CornerType.ALL);
containerLayout.setCornerRadius(2f, CornerType.BOTTOM_LEFT);
Other choices
public final enum class CornerType private constructor() : kotlin.Enum<com.jcminarro.roundkornerlayout.CornerType> {
ALL,
TOP_LEFT,
TOP_RIGHT,
BOTTOM_RIGHT,
BOTTOM_LEFT;
}
try this :
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
app:cardCornerRadius="20dp">
<ImageView
android:id="#+id/image_view"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_gravity="top|right"
android:scaleType="fitXY"
android:src="#drawable/person" />
</androidx.cardview.widget.CardView>
and in your activity :
ImageView image = findViewById(R.id.image_view);
Bitmap bitImg = BitmapFactory.decodeResource(getResources(),
R.drawable.person);
image.setImageBitmap(createRoundedRectBitmap(bitImg, 0, 20, 0, 20));
}
private static Bitmap createRoundedRectBitmap(#NonNull Bitmap bitmap, float topLeftCorner, float topRightCorner, float bottomRightCorner,
float bottomLeftCorner) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = Color.WHITE;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
Path path = new Path();
float[] radii = new float[]{
topLeftCorner, bottomLeftCorner,
topRightCorner, topRightCorner,
bottomRightCorner, bottomRightCorner,
bottomLeftCorner, bottomLeftCorner
};
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
path.addRoundRect(rectF, radii, Path.Direction.CW);
canvas.drawPath(path, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
This is simple just make drawable resource file text_logo_fix.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#fff"/>
<corners android:bottomLeftRadius="30dp" android:topRightRadius="30dp"/>
</shape>
and set this drawable file in ImageView property android:background
<ImageView
android:id="#+id/imageView"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="#drawable/herenamedrawableresourcefile"
android:layout_gravity="center_horizontal"
android:src="#drawable/text_logo_fix" />
or you can look like this way
<LinearLayout
android:padding="10dp"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/herenamedrawableresourcefile">
<ImageView
android:id="#+id/imageView"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center_horizontal"
android:src="#drawable/text_logo_fix" />
</LinearLayout>

Android shape drawable color is displayed incorrectly

I'm trying to draw a simple circle and use it as a background to an ImageView the problem is the circle is drawn with different color whenever I open the application, here is my code.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<size
android:width="16dp"
android:height="16dp"
/>
<solid android:color="#FFF6621F"/>
<ImageView
android:id="#+id/counterBackground"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/shape_circle"/>
You can use following code....
activity_main.xml
<LinearLayout
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_gravity="center">
<ImageView
android:id="#+id/imgview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
ImageView imgview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgview = (ImageView) findViewById(R.id.imgview);
Bitmap bm = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_blogger);
imgview.setImageBitmap(getCircleBitmap(bm));
}
private Bitmap getCircleBitmap(Bitmap bitmap) {
final Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(output);
final int color = Color.RED;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawOval(rectF, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
bitmap.recycle();
return output;
}
}
You can use getCircleBitmap() method for make ImageView in circle shape.

Android : ViewGroup background transparency

I have an issue with a transparent CircleView (which extends ImageView and is a square). I made a circular image translate over my CircleView. The problem I encounter is the following :
The gray background you see is a RelativeLayout, I want to hide each corner thanks to the onDraw of my CircleView, because thanks to this feature I will be able to translate the image without showing it outside the circle.
#Override
protected void onDraw(Canvas canvas) {
int circleCenter = getHeight() / 2;
radius = circleCenter;
loadBitmap();
if(hideBackground) {
Path circlePath = new Path();
circlePath.addCircle(circleCenter, circleCenter, radius, Path.Direction.CCW);
circlePath.setFillType(Path.FillType.INVERSE_EVEN_ODD);
paint.setColor(0x00000000);
paint.setShader(null);
canvas.drawPath(circlePath, paint);
} else {
if (image != null) {
radius -= 5;
paint.setShader(computeBitmapShader(image));
canvas.drawCircle(circleCenter, circleCenter, radius, paint);
}
}
}
And my layout if needed :
<RelativeLayout
android:id="#+id/wheel_layout"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="0.45"
android:background="#4F4F4F">
<CircleView
android:id="#+id/wheel"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:id="#+id/counter"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:textColor="#FFF"
android:text="\?"
android:textStyle="bold"
android:textSize="66dp"
android:gravity="center_vertical|center_horizontal"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
So what I want is to draw a transparent background over the background of my RelativeLayout, do you have any idea ?
You should do something like that in your onDraw() method:
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = bitmap.getHeight() / 2;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
Read this for more info: PorterDuff

How to scale an own drawable in ImageView

i tried to add an own drawable object to an ImageView. i want that the drawable fits the ImageView. But if my resolution is to small the drawable is bigger than the ImageView.
Here my ImagaView:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
...
<ImageView
android:layout_width="match_parent"
android:layout_height="250dip"
android:id="#+id/tvWeekStats"
android:layout_below="#+id/llTimer"
android:layout_margin="5dip"
android:scaleType="fitXY"
android:adjustViewBounds="true"
/>
</RelativeLayout>
</ScrollView>
And here is my drawable:
public class WeekdayDrawable extends Drawable {
private Paint paint;
public WeekdayDrawable() {
this(new StatsWeekday());
}
public WeekdayDrawable(StatsWeekday ownTeam) {
paint = new Paint();
paint.setStyle(Style.FILL);
}
#Override
public void draw(Canvas canvas) {
try {
canvas.save();
paint.setColor(Color.WHITE);
canvas.drawLine(0, 0, 700, 0, paint);
canvas.drawLine(0, 10, 600, 10, paint);
canvas.drawLine(0, 20, 500, 20, paint);
canvas.drawLine(0, 30, 400, 30, paint);
canvas.drawLine(0, 40, 300, 40, paint);
canvas.drawRect(33, 60, 77, 77, paint );
paint.setColor(Color.YELLOW);
canvas.drawRect(33, 33, 77, 60, paint );
paint.setColor(Color.WHITE);
paint.setTextSize(20);
canvas.drawText("Some Text", 10, 25, paint);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void setAlpha(int alpha) {
// Has no effect
}
#Override
public void setColorFilter(ColorFilter cf) {
// Has no effect
}
#Override
public int getOpacity() {
// Not Implemented
return 0;
}
}
Drawable weekStats;
weekStats = new WeekdayDrawable(weekDayData);
tvWeekStats.setImageDrawable(weekStats);
Thanks for any help
You shouldn't use static width and height like this canvas.drawLine(0, 0, 700, 0, paint);.
Use Fractions of getHeight() and getWidth() instead, like:
canvas.drawLine(0, 0, getHeight()/2, 0, paint);
or so. Then the scalingproblem solves itself
1) Make sure your ImageView has these attributes:
android:adjustViewBounds="true"
android:scaleType="centerInside"
This should center the image and fit it within your imageview.
2) For some apparent reason drawables like that wont be subject to the attributes. It appears that it must be a bitmap or imageResource for the attributes to affect the image. In other words CONVERT your drawable into a bitmap. Here is a pre-written code which I took from: https://stackoverflow.com/a/10600736/1371041
public static Bitmap drawableToBitmap (Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable)drawable).getBitmap();
}
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
3) Use the method to convert it into a bitmap and set it using this:
myImageView.setImageBitmap(drawableToBitmap(weekStats));

Mask ImageView with round corner background

I am having a Custom ListView which contains an ImageView and TextView. Everything is working fine.
What I want is the image is displayed in list are in round corner. From the Webservice i get the images in rectangle shape. But i want to display it in Round corner ImageView as below.
Can anyone show me the way how can i mask the image in round corner?
I already tried by creating the drawable file as below and applied it as src in ImageView. But nothing working for me.
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="oval" >
<solid android:color="#FFFFFF" />
<padding
android:bottom="10dp"
android:left="10dp"
android:right="10dp"
android:top="10dp" />
<corners android:radius="5dp" />
</shape>
</item>
<item>
<shape android:shape="oval" >
<padding
android:bottom="5dp"
android:left="5dp"
android:right="5dp"
android:top="5dp" />
<solid android:color="#FFFFFF" />
</shape>
</item>
</layer-list>
EDITED:
I have Applied below solution:
<FrameLayout
android:id="#+id/imagemaskframe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp" >
<ImageView
android:id="#+id/op_ivpic"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_gravity="center"
android:scaleType="fitXY" />
<ImageView
android:id="#+id/iv_mask_op"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_gravity="center"
android:adjustViewBounds="true"
android:scaleType="fitXY"
android:src="#drawable/imgmask" />
</FrameLayout>
The best way is to do it in Canvas using PorterDuff operations and/or Shaders. Let's say your Bitmap is available and stored in mBitmap.
Option 1: Using Shaders.
#Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Load the bitmap as a shader to the paint.
final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
final Shader shader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
paint.setShader(shader);
// Draw a circle with the required radius.
final float halfWidth = canvas.getWidth()/2;
final float halfHeight = canvas.getHeight()/2;
final float radius = Math.max(halfWidth, halfHeight);
canvas.drawCircle(halfWidth, halfHeight, radius, paint);
}
Option 2: Using PorterDuff mode.
#Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Create a circular path.
final float halfWidth = canvas.getWidth()/2;
final float halfHeight = canvas.getHeight()/2;
final float radius = Math.max(halfWidth, halfHeight);
final Path path = new Path();
path.addCircle(halfWidth, halfHeight, radius, Path.Direction.CCW);
final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
canvas.drawPath(path, paint);
}
Note:
It's not good to create objects inside onDraw() calls. Hence you should have your paint and shader initially somewhere else. This could probably be done when you set the image bitmap to the view.
Canvas might need to be saved and restored when it is not backed by a hardware texture. The general ideas around it are not mentioned here.
Remember to add setWillNotDraw(false); to the constructor.
Additional References:
https://sriramramani.wordpress.com/2012/12/21/shaders/ has information on Shaders.
http://mxr.mozilla.org/mozilla-central/source/mobile/android/base/ShapedButton.java uses Path to curved button in Firefox for Android.
http://sriramramani.wordpress.com/2012/08/27/constructing-squishy-buttons/ has information on Canvas saving, restoring and special cases for pre-ICS.
I'd definite recommend Picasso, as others have. This bit of code for one of my Activity classes did the trick for me. It utilized a color I had defined in color.xml and a simple layout (shown below).
ImageView profile_image = (ImageView) findViewById(R.id.profile_image);
mContext = profile_image.getContext();
// ----------------------------------------------------------------
// apply rounding to image
// see: https://github.com/vinc3m1/RoundedImageView
// ----------------------------------------------------------------
Transformation transformation = new RoundedTransformationBuilder()
.borderColor(getResources().getColor(R.color.my_special_orange))
.borderWidthDp(5)
.cornerRadiusDp(50)
.oval(false)
.build();
Picasso.with(mContext)
.load("http://{some_url}.jpg")
.fit()
.transform(transformation)
.into(profile_image);
And the corresponding Layout file:
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="120dp"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:padding="12dp">
<ImageView
android:id="#+id/profile_image"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_gravity="center"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_gravity="center"
android:padding="12dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="First-Name"
android:id="#+id/profile_first_name"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Lastname"
android:id="#+id/profile_last_name" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
Here's the result:
I suggest you to use another method:
One FrameLayout and two ImageView can do it.
<FrameLayout>
<ImageView /> your image
<ImageView /> put a image which has a transparent circle in it
</FrameLayout>
then your image can been seen via transparent circle.
A RoundedBitmapDrawable from the v4 Support Library can be applied to an ImageView to achieve the desired effect:
ImageView imageView = (ImageView)findViewById(R.id.imageView);
Bitmap avatar = BitmapFactory.decodeResource(getResources(), R.drawable.avatar);
RoundedBitmapDrawable roundDrawable = RoundedBitmapDrawableFactory.create(getResources(), avatar);
roundDrawable.setCircular(true);
imageView.setImageDrawable(roundDrawable);
A simple solution and without a black background!
public class CircleImageView extends ImageView
{
public CircleImageView(Context context)
{
super(context);
}
#Override
protected void onDraw(Canvas canvas)
{
// Create a circular path.
final float halfWidth = canvas.getWidth()/2;
final float halfHeight = canvas.getHeight()/2;
final float radius = Math.max(halfWidth, halfHeight);
final Path path = new Path();
path.addCircle(halfWidth, halfHeight, radius, Path.Direction.CCW);
canvas.clipPath(path);
super.onDraw(canvas);
}
}
Refer the following code, that exactly do what u want.
https://github.com/vinc3m1/RoundedImageView
As you said if you dont want custom view then try the following idea
create 9 patch .png image (like photo frame) with rounded corner and transparent background
then create Relative layout / FrameLayout with two image views as like follows
<RelativeLayout ....>
<ImageView android:id="#+id/myImage" ..>
<ImageView android:id="#+id/myRoundCorner" android:src="#drawable/myRoundCornerdFrame">
</RelativeLayout>
make sure that both the image views having same attributes except image source, and also make sure that image view which has source as myRoundCornerFrame should be over(top) the another image view.
Just try android-shape-imageview - it should helps you.
For those already using Glide, you can achieve the effect with RequestOptions:
RequestOptions requestOptions = new RequestOptions();
requestOptions = requestOptions.transforms(new CenterCrop(), new RoundedCorners(radiusInPixels));
Glide.with(context)
.load(imageUrl)
.apply(requestOptions)
.into(imageView);
here what I did ..but my bg img was rectangle .
ImageView ivLogo;
ivLogo=(ImageView)fragment.mRoot.findViewById(R.id.iv_offer_logo);
then while setting the image ,
if(response.result.Partner.logo_url != null && !response.result.Partner.logo_url.equals("")){
ivLogo.setPadding(3,3,3,3);
DisplayImageOptions options =
WWFunctions.getDisplayImage(0);
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(mOfferDetailsFragment.getActivity() ));
imageLoader.displayImage(response.result.Partner.logo_url, ivLogo, options);
}
make a xml file with name roundimage.xml in drawable hdpi folder and try the following code.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#android:color/darker_gray" />
<corners android:bottomRightRadius="50dip"
android:bottomLeftRadius="50dip"
android:topRightRadius="50dip"
android:topLeftRadius="50dip"/>
</shape>
then include the file to your image background as
android:background="#drawable/roundimage"
I request you to change the dimensions and colors as per your requirements.
please use this code
package com.company.app.utils;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Bitmap.Config;
import android.graphics.PorterDuff.Mode;
public class ImageHelper {
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap
.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float 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 output;
}
}
use this as this works.
if you want square cornered then use this
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;
}
Also, I overrode ImageView to put this in so I could define it in xml. You may want to add in some of the logic that the super call makes here, but I've commented it as it's not helpful in my case.
#Override
protected void onDraw(Canvas canvas) {
//super.onDraw(canvas);
Drawable drawable = getDrawable();
Bitmap b = ((BitmapDrawable)drawable).getBitmap() ;
Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);
int w = getWidth(), h = getHeight();
Bitmap roundBitmap=CropImageView.getRoundedCornerBitmap( getContext(),
bitmap,10, w, h , true, false,true, false);
canvas.drawBitmap(roundBitmap, 0,0 , null);
}
Expanding on sriramramani's answer (including the fix for black background), here is my simple ImageView in its entirety:
public class ExampleImageView extends ImageView {
public ExampleImageView(Context context) {
super(context);
init();
}
public ExampleImageView(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public ExampleImageView(Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
void init() {
setWillNotDraw(false);
}
#Override
protected void onDraw(Canvas canvas) {
int count = canvas.saveLayer(0, 0, getWidth(), getHeight(), null,
Canvas.MATRIX_SAVE_FLAG |
Canvas.CLIP_SAVE_FLAG |
Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
Canvas.FULL_COLOR_LAYER_SAVE_FLAG |
Canvas.CLIP_TO_LAYER_SAVE_FLAG);
super.onDraw(canvas);
// Create a circular path.
final float halfWidth = canvas.getWidth()/2;
final float halfHeight = canvas.getHeight()/2;
final float radius = Math.max(halfWidth, halfHeight);
final Path path = new Path();
path.addCircle(halfWidth, halfHeight, radius, Path.Direction.CCW);
final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
canvas.drawPath(path, paint);
canvas.restoreToCount(count);
}
}
One thing- if I remove this line:
setWillNotDraw(false);
Everything still works. Not sure if it is needed?

Categories

Resources