Button Pressed Background is Transparent Before Clicked - android

I have implement Ripple Animation after the button is pressed. Everything works great except before I Click the Button is Transparent makes it impossible to be visible.
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="?android:colorControlHighlight">
<item android:id="#android:id/mask">
<shape android:shape="rectangle">
<corners android:radius="3dp"/>
<solid android:color="?android:colorAccent" />
</shape>
</item>
</ripple>
This is the Custom Button Class I have created.
public class MyButton extends Button {
public MyButton(final Context context) {
super(context);
init();
}
public MyButton(final Context context, final AttributeSet attrs) {
super(context, attrs);
init();
}
public MyButton(final Context context, final AttributeSet attrs,
final int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
mPaint = new Paint();
mPaint.setAlpha(100);
}
#Override
public boolean onTouchEvent(#NonNull final MotionEvent event) {
if (event.getActionMasked() == MotionEvent.ACTION_UP) {
mDownX = event.getX();
mDownY = event.getY();
ObjectAnimator animator = ObjectAnimator.ofFloat(this, "radius", 0,
getWidth() * 3.0f);
animator.setInterpolator(new AccelerateInterpolator());
animator.setDuration(400);
animator.start();
}
return super.onTouchEvent(event);
}
public void setRadius(final float radius) {
mRadius = radius;
if (mRadius > 0) {
RadialGradient radialGradient = new RadialGradient(mDownX, mDownY,
mRadius * 3, Color.TRANSPARENT, getResources().getColor(R.color.colorPrimaryDark),
Shader.TileMode.MIRROR);
mPaint.setShader(radialGradient);
}
invalidate();
}
private Path mPath = new Path();
private Path mPath2 = new Path();
#Override
protected void onDraw(#NonNull final Canvas canvas) {
super.onDraw(canvas);
mPath2.reset();
mPath2.addCircle(mDownX, mDownY, mRadius, Path.Direction.CW);
canvas.clipPath(mPath2);
mPath.reset();
mPath.addCircle(mDownX, mDownY, mRadius / 3, Path.Direction.CW);
canvas.clipPath(mPath, Region.Op.DIFFERENCE);
canvas.drawCircle(mDownX, mDownY, mRadius, mPaint);
}
}
Here is where I have used the myButton class
<io.wyntr.peepster.MyButton
android:layout_width="325dp"
android:layout_height="60dp"
android:layout_marginTop="10dp"
android:textSize="20dp"
android:textAllCaps="false"
android:text="Continue"
android:id="#+id/sendCodeButton"
style="#style/Widget.AppCompat.Button.Borderless"
android:clickable="true"
android:background="#drawable/ripple"
android:textColor="#color/icons"
android:layout_gravity="center_horizontal" />
Screenshots:

Was waiting for you to respond to my comment, but gonna go on ahead and add my answer:
You can set the color of the button that will be using your ripple animation by adding the
<item android:drawable="#android:color/holo_blue_bright" />
Like so:
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="?android:colorControlHighlight">
<item android:id="#android:id/mask">
<shape android:shape="rectangle">
<corners android:radius="3dp" />
<solid android:color="?android:colorAccent" />
</shape>
</item>
<item android:drawable="#android:color/holo_blue_bright" />
</ripple>
Tested this. And when used, the default color (unpressed) for the button turns to holo_blue_bright. Here's a post that I think is useful for you. :)
Hope this helps. Cheers. :)

This line removes the border of your button so of course it will be invisible
try changing it to something else
style="#style/Widget.AppCompat.Button.Borderless"

Related

Bitmap with rounded convers

I want to make Bitmap rounded, but in result bitmap I have only left-top , and left-bottom corners become rounded. How to make all corners rounded?
#Override
public Bitmap transform(Bitmap source) {
Bitmap output = Bitmap.createBitmap(source.getWidth(), source.getHeight(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int cornerSizePx = 28;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, source.getWidth(), source.getHeight());
final RectF rectF = new RectF(rect);
// prepare canvas for transfer
paint.setAntiAlias(true);
paint.setColor(0xFFFFFFFF);
paint.setStyle(Paint.Style.FILL);
canvas.drawARGB(0, 0, 0, 0);
canvas.drawRoundRect(rectF, cornerSizePx, cornerSizePx, paint);
// draw source
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(source, rect, rect, paint);
return output;
}
Here is my source bitmap:
Here is result Bitmap
But I expected this:
Make Custom ImageView
Create Java class name CutomImageView.
Paste Following Code into that class.
public class CustomImageView extends ImageView {
public static float radius = 25.0f;
public CustomImageView(Context context) {
super(context);
}
public CustomImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
protected void onDraw(Canvas canvas) {
//float radius = 36.0f;
Path clipPath = new Path();
RectF rect = new RectF(0, 0, this.getWidth(), this.getHeight());
clipPath.addRoundRect(rect, radius, radius, Path.Direction.CW);
canvas.clipPath(clipPath);
super.onDraw(canvas);
}}
In layout use this
<your package name.CustomImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/thumbimg"
android:layout_marginTop="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:visibility="gone"
/>
<?xml version="1.0" encoding="utf-8"?>
<item android:state_pressed="true">
<shape >
<solid android:color="#color/colorPrimaryDark"/>
<corners
android:radius="30dp"/>
</shape>
</item>
<item android:state_focused="true" >
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#color/colorPrimaryDark"/>
<corners
android:radius="30dp"/>
</shape>
</item>
<item android:state_focused="false" >
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#color/colorPrimary"/>
<corners
android:radius="30dp"/>
</shape>
</item>
<item android:state_pressed="false" >
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#color/colorPrimary"/>
<corners
android:radius="30dp"
/>
</shape>
</item>
put this code inside a new drawable file then use this new drawable file as a background of your image

Children of ListView doesn't respect parents border radius [duplicate]

I am trying to make a view in android with rounded edges. The solution I found so far is to define a shape with rounded corners and use it as the background of that view.
Here is what I did, define a drawable as given below:
<padding
android:top="2dp"
android:bottom="2dp"/>
<corners android:bottomRightRadius="20dp"
android:bottomLeftRadius="20dp"
android:topLeftRadius="20dp"
android:topRightRadius="20dp"/>
Now I used this as the background for my layout as below:
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"
android:clipChildren="true"
android:background="#drawable/rounded_corner">
This works perfectly fine, I can see that the view has rounded edges.
But my layout has got many other child views in it, say an ImageView or a MapView. When I place an ImageView inside the above layout, the corners of image are not clipped/cropped, instead it appears full.
I have seen other workarounds to make it work like the one explained here.
But is there a method to set rounded corners for a view and all its
child views are contained within that main view that has rounded
corners?
Another approach is to make a custom layout class like the one below. This layout first draws its contents to an offscreen bitmap, masks the offscreen bitmap with a rounded rect and then draws the offscreen bitmap on the actual canvas.
I tried it and it seems to work (at least for my simple testcase). It will of course affect performance compared to a regular layout.
package com.example;
import android.content.Context;
import android.graphics.*;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.widget.FrameLayout;
public class RoundedCornerLayout extends FrameLayout {
private final static float CORNER_RADIUS = 40.0f;
private Bitmap maskBitmap;
private Paint paint, maskPaint;
private float cornerRadius;
public RoundedCornerLayout(Context context) {
super(context);
init(context, null, 0);
}
public RoundedCornerLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, 0);
}
public RoundedCornerLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs, defStyle);
}
private void init(Context context, AttributeSet attrs, int defStyle) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
cornerRadius = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, CORNER_RADIUS, metrics);
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
maskPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
maskPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
setWillNotDraw(false);
}
#Override
public void draw(Canvas canvas) {
Bitmap offscreenBitmap = Bitmap.createBitmap(canvas.getWidth(), canvas.getHeight(), Bitmap.Config.ARGB_8888);
Canvas offscreenCanvas = new Canvas(offscreenBitmap);
super.draw(offscreenCanvas);
if (maskBitmap == null) {
maskBitmap = createMask(canvas.getWidth(), canvas.getHeight());
}
offscreenCanvas.drawBitmap(maskBitmap, 0f, 0f, maskPaint);
canvas.drawBitmap(offscreenBitmap, 0f, 0f, paint);
}
private Bitmap createMask(int width, int height) {
Bitmap mask = Bitmap.createBitmap(width, height, Bitmap.Config.ALPHA_8);
Canvas canvas = new Canvas(mask);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.WHITE);
canvas.drawRect(0, 0, width, height, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
canvas.drawRoundRect(new RectF(0, 0, width, height), cornerRadius, cornerRadius, paint);
return mask;
}
}
Use this like a normal layout:
<com.example.RoundedCornerLayout
android:layout_width="200dp"
android:layout_height="200dp">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/test"/>
<View
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#ff0000"
/>
</com.example.RoundedCornerLayout>
Or you can use a android.support.v7.widget.CardView like so:
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
card_view:cardBackgroundColor="#color/white"
card_view:cardCornerRadius="4dp">
<!--YOUR CONTENT-->
</android.support.v7.widget.CardView>
shape.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#f6eef1" />
<stroke
android:width="2dp"
android:color="#000000" />
<padding
android:bottom="5dp"
android:left="5dp"
android:right="5dp"
android:top="5dp" />
<corners android:radius="5dp" />
</shape>
and inside you layout
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"
android:clipChildren="true"
android:background="#drawable/shape">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/your image"
android:background="#drawable/shape">
</LinearLayout>
Jaap van Hengstum's answer works great however I think it is expensive and if we apply this method on a Button for example, the touch effect is lost since the view is rendered as a bitmap.
For me the best method and the simplest one consists in applying a mask on the view, like that:
#Override
protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {
super.onSizeChanged(width, height, oldWidth, oldHeight);
float cornerRadius = <whatever_you_want>;
this.path = new Path();
this.path.addRoundRect(new RectF(0, 0, width, height), cornerRadius, cornerRadius, Path.Direction.CW);
}
#Override
protected void dispatchDraw(Canvas canvas) {
if (this.path != null) {
canvas.clipPath(this.path);
}
super.dispatchDraw(canvas);
}
Create a xml file called round.xml in the drawable folder and paste this content:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="#FFFFFF" />
<stroke android:width=".05dp" android:color="#d2d2d2" />
<corners android:topLeftRadius="5dp" android:topRightRadius="5dp" android:bottomRightRadius="5dp" android:bottomLeftRadius="5dp"/>
</shape>
then use the round.xml as background to any item. Then it will give you rounded corners.
If you are having problem while adding touch listeners to the layout. Use this layout as parent layout.
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.Region;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.widget.FrameLayout;
public class RoundedCornerLayout extends FrameLayout {
private final static float CORNER_RADIUS = 6.0f;
private float cornerRadius;
public RoundedCornerLayout(Context context) {
super(context);
init(context, null, 0);
}
public RoundedCornerLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, 0);
}
public RoundedCornerLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs, defStyle);
}
private void init(Context context, AttributeSet attrs, int defStyle) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
cornerRadius = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, CORNER_RADIUS, metrics);
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
#Override
protected void dispatchDraw(Canvas canvas) {
int count = canvas.save();
final Path path = new Path();
path.addRoundRect(new RectF(0, 0, canvas.getWidth(), canvas.getHeight()), cornerRadius, cornerRadius, Path.Direction.CW);
canvas.clipPath(path, Region.Op.REPLACE);
canvas.clipPath(path);
super.dispatchDraw(canvas);
canvas.restoreToCount(count);
}
}
as
<?xml version="1.0" encoding="utf-8"?>
<com.example.view.RoundedCornerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="#+id/patentItem"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingRight="20dp">
... your child goes here
</RelativeLayout>
</com.example.view.RoundedCornerLayout>
In case you want to round some specific corner.
fun setCorners() {
val mOutlineProvider = object : ViewOutlineProvider() {
override fun getOutline(view: View, outline: Outline) {
val left = 0
val top = 0;
val right = view.width
val bottom = view.height
val cornerRadiusDP = 16f
val cornerRadius = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, cornerRadiusDP, resources.displayMetrics).toInt()
// all corners
outline.setRoundRect(left, top, right, bottom, cornerRadius.toFloat())
/* top corners
outline.setRoundRect(left, top, right, bottom+cornerRadius, cornerRadius.toFloat())*/
/* bottom corners
outline.setRoundRect(left, top - cornerRadius, right, bottom, cornerRadius.toFloat())*/
/* left corners
outline.setRoundRect(left, top, right + cornerRadius, bottom, cornerRadius.toFloat())*/
/* right corners
outline.setRoundRect(left - cornerRadius, top, right, bottom, cornerRadius.toFloat())*/
/* top left corner
outline.setRoundRect(left , top, right+ cornerRadius, bottom + cornerRadius, cornerRadius.toFloat())*/
/* top right corner
outline.setRoundRect(left - cornerRadius , top, right, bottom + cornerRadius, cornerRadius.toFloat())*/
/* bottom left corner
outline.setRoundRect(left, top - cornerRadius, right + cornerRadius, bottom, cornerRadius.toFloat())*/
/* bottom right corner
outline.setRoundRect(left - cornerRadius, top - cornerRadius, right, bottom, cornerRadius.toFloat())*/
}
}
myView.apply {
outlineProvider = mOutlineProvider
clipToOutline = true
}
}
Can be used on a LinearLayout with children that looks like this:
to this:
With the Material Components Library the best way to make a View with rounded corners is to use the MaterialShapeDrawable.
Create a ShapeAppearanceModel with custom rounded corners:
ShapeAppearanceModel shapeAppearanceModelLL1 = new ShapeAppearanceModel()
.toBuilder()
.setAllCorners(CornerFamily.ROUNDED,radius16)
.build();
Create a MaterialShapeDrawable:
MaterialShapeDrawable shapeDrawableLL1 = new MaterialShapeDrawable(shapeAppearanceModeLL1);
If you want to apply also an elevationOverlay for the dark theme use this:
MaterialShapeDrawable shapeDrawableLL1 = MaterialShapeDrawable.createWithElevationOverlay(this, 4.0f);
shapeDrawableLL1.setShapeAppearanceModel(shapeAppearanceModelLL1);
Optional: apply to the shapeDrawable a background color and a stroke
shapeDrawableLL1.setFillColor(
ContextCompat.getColorStateList(this,R.color...));
shapeDrawableLL1.setStrokeWidth(2.0f);
shapeDrawableLL1.setStrokeColor(
ContextCompat.getColorStateList(this,R.color...));
Finally apply the shapeDrawable as background in your LinearLayout (or other view):
LinearLayout linearLayout1= findViewById(R.id.ll_1);
ViewCompat.setBackground(linearLayout1,shapeDrawableLL1);
In Android L you will be able to just use View.setClipToOutline to get that effect. In previous versions there is no way to just clip the contents of a random ViewGroup in a certain shape.
You will have to think of something that would give you a similar effect:
If you only need rounded corners in the ImageView, you can use a shader to 'paint' the image over the shape you are using as background. Take a look at this library for an example.
If you really need every children to be clipped, maybe you can another view over your layout? One with a background of whatever color you are using, and a round 'hole' in the middle? You could actually create a custom ViewGroup that draws that shape over every children overriding the onDraw method.
Create a xml file under your drawable folder with following code. (The name of the file I created is rounded_corner.xml)
rounded_corner.xml
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<!-- view background color -->
<solid
android:color="#a9c5ac" >
</solid>
<!-- view border color and width -->
<stroke
android:width="3dp"
android:color="#1c1b20" >
</stroke>
<!-- If you want to add some padding -->
<padding
android:left="4dp"
android:top="4dp"
android:right="4dp"
android:bottom="4dp" >
</padding>
<!-- Here is the corner radius -->
<corners
android:radius="10dp" >
</corners>
</shape>
And keep this drawable as background for the view to which you want to keep rounded corner border. Let’s keep it for a LinearLayout
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/rounded_corner"
android:layout_centerInParent="true">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hi, This layout has rounded corner borders ..."
android:gravity="center"
android:padding="5dp"/>
</LinearLayout>
The CardView worked for me in API 27 in Android Studio 3.0.1. The colorPrimary was referenced in the res/values/colors.xml file and is just an example. For the layout_width of 0dp it will stretch to the width of the parent. You'll have to configure the constraints and width/height to your needs.
<android.support.v7.widget.CardView
android:id="#+id/cardView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:cardCornerRadius="4dp"
app:cardBackgroundColor="#color/colorPrimary">
<!-- put your content here -->
</android.support.v7.widget.CardView>
You can use an androidx.cardview.widget.CardView like so:
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardCornerRadius="#dimen/dimen_4"
app:cardElevation="#dimen/dimen_4"
app:contentPadding="#dimen/dimen_10">
...
</androidx.cardview.widget.CardView>
OR
shape.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#f6eef1" />
<stroke
android:width="2dp"
android:color="#000000" />
<padding
android:bottom="5dp"
android:left="5dp"
android:right="5dp"
android:top="5dp" />
<corners android:radius="5dp" />
</shape>
and inside you layout
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/shape">
...
</LinearLayout>
To create round corner image using com.google.android.material:material:1.2.0-beta01
float radius = context.getResources().getDimension(R.dimen.border_radius_hug);
shapeAppearanceModel = new ShapeAppearanceModel()
.toBuilder()
.setAllCorners(CornerFamily.ROUNDED,radius)
.build();
imageView.setShapeAppearanceModel(shapeAppearanceModel)
or if you want to use it in xml file:
<com.google.android.material.imageview.ShapeableImageView
android:id="#+id/thumb"
android:layout_width="80dp"
android:layout_height="60dp"
app:shapeAppearanceOverlay="#style/circleImageView"
/>
in style.xml add this:
<style name="circleImageView" parent="">
<item name="cornerFamily">rounded</item>
<item name="cornerSize">10%</item>
</style>
follow this tutorial and all the discussion beneath it -
http://www.curious-creature.org/2012/12/11/android-recipe-1-image-with-rounded-corners/
according to this post written by Guy Romain, one of the leading developers of the entire Android UI toolkit, it is possible to make a container (and all his child views) with rounded corners, but he explained that it too expensive (from performances of rendering issues).
I'll recommend you to go according to his post, and if you want rounded corners, then implement rounded corners ImageView according to this post. then, you could place it inside a container with any background, and you'll get the affect you wish.
that's what I did also also eventually.
public class RoundedCornerLayout extends FrameLayout {
private double mCornerRadius;
public RoundedCornerLayout(Context context) {
this(context, null, 0);
}
public RoundedCornerLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RoundedCornerLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs, defStyle);
}
private void init(Context context, AttributeSet attrs, int defStyle) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
public double getCornerRadius() {
return mCornerRadius;
}
public void setCornerRadius(double cornerRadius) {
mCornerRadius = cornerRadius;
}
#Override
public void draw(Canvas canvas) {
int count = canvas.save();
final Path path = new Path();
path.addRoundRect(new RectF(0, 0, canvas.getWidth(), canvas.getHeight()), (float) mCornerRadius, (float) mCornerRadius, Path.Direction.CW);
canvas.clipPath(path, Region.Op.REPLACE);
canvas.clipPath(path);
super.draw(canvas);
canvas.restoreToCount(count);
}
}
Difference from Jaap van Hengstum's answer:
Use BitmapShader instead of mask bitmap.
Create bitmap only once.
public class RoundedFrameLayout extends FrameLayout {
private Bitmap mOffscreenBitmap;
private Canvas mOffscreenCanvas;
private BitmapShader mBitmapShader;
private Paint mPaint;
private RectF mRectF;
public RoundedFrameLayout(Context context) {
super(context);
init();
}
public RoundedFrameLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public RoundedFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
setWillNotDraw(false);
}
#Override
public void draw(Canvas canvas) {
if (mOffscreenBitmap == null) {
mOffscreenBitmap = Bitmap.createBitmap(canvas.getWidth(), canvas.getHeight(), Bitmap.Config.ARGB_8888);
mOffscreenCanvas = new Canvas(mOffscreenBitmap);
mBitmapShader = new BitmapShader(mOffscreenBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setShader(mBitmapShader);
mRectF = new RectF(0f, 0f, canvas.getWidth(), canvas.getHeight());
}
super.draw(mOffscreenCanvas);
canvas.drawRoundRect(mRectF, 8, 8, mPaint);
}
}
The tutorial link you provided seems to suggest that you need to set the layout_width and layout_height properties, of your child elements to match_parent.
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent">
try this property with your linear layout it will help
tools:context=".youractivity"
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels) {
Bitmap roundedBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap
.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(roundedBitmap);
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 roundedBitmap;
}
I have seen many solutions, but most of them are useless with Image
View unless you change Image View to other design components, and I do
not recommend them because they may not be compatible with some
**
solution using:
**
Width and color of stroke in drawable
And Margin for the picture
versions. Here is the quick solution.
The first step:
<RelativeLayout
android:layout_width="90dp"
android:layout_height="90dp">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:scaleType="centerCrop"
android:src="#drawable/a" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/card_helh" />
</RelativeLayout>
design shape
The second step:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="#dimen/_10dp"/>
<stroke android:color="#color/white" android:width="5dp"/>
</shape>
**
A note
** about setting the night mode, set the color stroke color to the color of the container's night so that it appears more homogeneous This
solution works 100%
This solution is mine and I am currently using it
Use shape in xml with rectangle.set the property of bottom or upper radius as want.then apply that xml as background to ur view....or...use gradients to do it from code.

Android round edges on ring shaped progressbar

I'm trying to make a circular progress bar on android and it seems pretty straightforward task , but I'm struggling with rounding the edges of the progress and secondary progress.
Is there a way to do that without making a custom view ? Using a corners radius ? or nine patch drawable ?
For this view (see attachement) I'm using a simple xml file
<item android:id="#android:id/progress">
<shape
android:useLevel="true"
android:innerRadius="#dimen/sixty_dp"
android:shape="ring"
android:thickness="#dimen/seven_dp">
<solid android:color="#477C5B"/>
<stroke android:width="1dip"
android:color="#FFFF"/>
</shape>
</item>
Just create class called MyProgress in your package .. and paste the following code..
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.View;
public class MyProgress extends View {
private Paint mPrimaryPaint;
private Paint mSecondaryPaint;
private RectF mRectF;
private TextPaint mTextPaint;
private Paint mBackgroundPaint;
private boolean mDrawText = false;
private int mSecondaryProgressColor;
private int mPrimaryProgressColor;
private int mBackgroundColor;
private int mStrokeWidth;
private int mProgress;
private int mSecodaryProgress;
private int mTextColor;
private int mPrimaryCapSize;
private int mSecondaryCapSize;
private boolean mIsPrimaryCapVisible;
private boolean mIsSecondaryCapVisible;
private int x;
private int y;
private int mWidth = 0, mHeight = 0;
public MyProgress(Context context) {
super(context);
init(context, null);
}
public MyProgress(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public MyProgress(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
void init(Context context, AttributeSet attrs) {
TypedArray a;
if (attrs != null) {
a = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.MyProgress,
0, 0);
} else {
throw new IllegalArgumentException("Must have to pass the attributes");
}
try {
mDrawText = a.getBoolean(R.styleable.MyProgress_showProgressText, false);
mBackgroundColor = a.getColor(R.styleable.MyProgress_backgroundColor, android.R.color.darker_gray);
mPrimaryProgressColor = a.getColor(R.styleable.MyProgress_progressColor, android.R.color.darker_gray);
mSecondaryProgressColor = a.getColor(R.styleable.MyProgress_secondaryProgressColor, android.R.color.black);
mProgress = a.getInt(R.styleable.MyProgress_progress, 0);
mSecodaryProgress = a.getInt(R.styleable.MyProgress_secondaryProgress, 0);
mStrokeWidth = a.getDimensionPixelSize(R.styleable.MyProgress_strokeWidth, 20);
mTextColor = a.getColor(R.styleable.MyProgress_textColor, android.R.color.black);
mPrimaryCapSize = a.getInt(R.styleable.MyProgress_primaryCapSize, 20);
mSecondaryCapSize = a.getInt(R.styleable.MyProgress_secodaryCapSize, 20);
mIsPrimaryCapVisible = a.getBoolean(R.styleable.MyProgress_primaryCapVisibility, true);
mIsSecondaryCapVisible = a.getBoolean(R.styleable.MyProgress_secodaryCapVisibility, true);
} finally {
a.recycle();
}
mBackgroundPaint = new Paint();
mBackgroundPaint.setAntiAlias(true);
mBackgroundPaint.setStyle(Paint.Style.STROKE);
mBackgroundPaint.setStrokeWidth(mStrokeWidth);
mBackgroundPaint.setColor(mBackgroundColor);
mPrimaryPaint = new Paint();
mPrimaryPaint.setAntiAlias(true);
mPrimaryPaint.setStyle(Paint.Style.STROKE);
mPrimaryPaint.setStrokeWidth(mStrokeWidth);
mPrimaryPaint.setColor(mPrimaryProgressColor);
mSecondaryPaint = new Paint();
mSecondaryPaint.setAntiAlias(true);
mSecondaryPaint.setStyle(Paint.Style.STROKE);
mSecondaryPaint.setStrokeWidth(mStrokeWidth - 2);
mSecondaryPaint.setColor(mSecondaryProgressColor);
mTextPaint = new TextPaint();
mTextPaint.setColor(mTextColor);
mRectF = new RectF();
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mRectF.set(getPaddingLeft(), getPaddingTop(), w - getPaddingRight(), h - getPaddingBottom());
mTextPaint.setTextSize(w / 5);
x = (w / 2) - ((int) (mTextPaint.measureText(mProgress + "%") / 2));
y = (int) ((h / 2) - ((mTextPaint.descent() + mTextPaint.ascent()) / 2));
mWidth = w;
mHeight = h;
invalidate();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mPrimaryPaint.setStyle(Paint.Style.STROKE);
mSecondaryPaint.setStyle(Paint.Style.STROKE);
// for drawing a full progress .. The background circle
canvas.drawArc(mRectF, 0, 360, false, mBackgroundPaint);
// for drawing a secondary progress circle
int secondarySwipeangle = (mSecodaryProgress * 360) / 100;
canvas.drawArc(mRectF, 270, secondarySwipeangle, false, mSecondaryPaint);
// for drawing a main progress circle
int primarySwipeangle = (mProgress * 360) / 100;
canvas.drawArc(mRectF, 270, primarySwipeangle, false, mPrimaryPaint);
// for cap of secondary progress
int r = (getHeight() - getPaddingLeft() * 2) / 2; // Calculated from canvas width
double trad = (secondarySwipeangle - 90) * (Math.PI / 180d); // = 5.1051
int x = (int) (r * Math.cos(trad));
int y = (int) (r * Math.sin(trad));
mSecondaryPaint.setStyle(Paint.Style.FILL);
if (mIsSecondaryCapVisible)
canvas.drawCircle(x + (mWidth / 2), y + (mHeight / 2), mSecondaryCapSize, mSecondaryPaint);
// for cap of primary progress
trad = (primarySwipeangle - 90) * (Math.PI / 180d); // = 5.1051
x = (int) (r * Math.cos(trad));
y = (int) (r * Math.sin(trad));
mPrimaryPaint.setStyle(Paint.Style.FILL);
if (mIsPrimaryCapVisible)
canvas.drawCircle(x + (mWidth / 2), y + (mHeight / 2), mPrimaryCapSize, mPrimaryPaint);
if (mDrawText)
canvas.drawText(mProgress + "%", x, y, mTextPaint);
}
public void setDrawText(boolean mDrawText) {
this.mDrawText = mDrawText;
invalidate();
}
public void setBackgroundColor(int mBackgroundColor) {
this.mBackgroundColor = mBackgroundColor;
invalidate();
}
public void setSecondaryProgressColor(int mSecondaryProgressColor) {
this.mSecondaryProgressColor = mSecondaryProgressColor;
invalidate();
}
public void setPrimaryProgressColor(int mPrimaryProgressColor) {
this.mPrimaryProgressColor = mPrimaryProgressColor;
invalidate();
}
public void setStrokeWidth(int mStrokeWidth) {
this.mStrokeWidth = mStrokeWidth;
invalidate();
}
public void setProgress(int mProgress) {
this.mProgress = mProgress;
invalidate();
}
public void setSecondaryProgress(int mSecondaryProgress) {
this.mSecodaryProgress = mSecondaryProgress;
invalidate();
}
public void setTextColor(int mTextColor) {
this.mTextColor = mTextColor;
invalidate();
}
public void setPrimaryCapSize(int mPrimaryCapSize) {
this.mPrimaryCapSize = mPrimaryCapSize;
invalidate();
}
public void setSecondaryCapSize(int mSecondaryCapSize) {
this.mSecondaryCapSize = mSecondaryCapSize;
invalidate();
}
public boolean isPrimaryCapVisible() {
return mIsPrimaryCapVisible;
}
public void setIsPrimaryCapVisible(boolean mIsPrimaryCapVisible) {
this.mIsPrimaryCapVisible = mIsPrimaryCapVisible;
}
public boolean isSecondaryCapVisible() {
return mIsSecondaryCapVisible;
}
public void setIsSecondaryCapVisible(boolean mIsSecondaryCapVisible) {
this.mIsSecondaryCapVisible = mIsSecondaryCapVisible;
}
public int getSecondaryProgressColor() {
return mSecondaryProgressColor;
}
public int getPrimaryProgressColor() {
return mPrimaryProgressColor;
}
public int getProgress() {
return mProgress;
}
public int getBackgroundColor() {
return mBackgroundColor;
}
public int getSecodaryProgress() {
return mSecodaryProgress;
}
public int getPrimaryCapSize() {
return mPrimaryCapSize;
}
public int getSecondaryCapSize() {
return mSecondaryCapSize;
}
}
and add the following line in res->values->attr.xml under a tag and build it
<declare-styleable name="MyProgress">
<attr name="showProgressText" format="boolean" />
<attr name="progress" format="integer" />
<attr name="secondaryProgress" format="integer" />
<attr name="progressColor" format="color" />
<attr name="secondaryProgressColor" format="color" />
<attr name="backgroundColor" format="color" />
<attr name="primaryCapSize" format="integer" />
<attr name="secodaryCapSize" format="integer" />
<attr name="primaryCapVisibility" format="boolean" />
<attr name="secodaryCapVisibility" format="boolean" />
<attr name="strokeWidth" format="dimension" />
<attr name="textColor" format="color" />
</declare-styleable>
that's it ....
and to use in your layout ..
<Your_Package_Name.MyProgress
android:padding="20dp"
android:id="#+id/timer1"
app:strokeWidth="10dp"
app:progress="30"
app:secondaryProgress="50"
app:backgroundColor="#android:color/black"
app:progressColor="#android:color/holo_blue_bright"
app:secondaryProgressColor="#android:color/holo_blue_dark"
app:primaryCapSize="30"
app:secodaryCapSize="40"
app:primaryCapVisibility="true"
app:secodaryCapVisibility="true"
android:layout_width="200dp"
android:layout_height="200dp" />
You can also change all property progrmatically using setMethods()...
feel free to ask anything ..
best of luck
[Update 23-01-2016]
finally I uploaded code on github.
You can refer it from here
https://github.com/msquare097/MProgressBar
Now You can use this ProgressBar by simply writing following line in your app build.gradle file. You don't have to copy above code.
compile 'com.msquare.widget.mprogressbar:mprogressbar:1.0.0'
I was able to achieve this using a layer list, and adding a dot to each side of the line. The first one will be stuck at the top, while the second one will follow the progress as an inset is added inside a rotate element. You will have to adjust it according to the size of your progressbar layout though. Mine is 250dp x 250dp.
progress_drawable.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<rotate android:fromDegrees="270" android:toDegrees="270">
<shape
android:innerRadiusRatio="2.55"
android:shape="ring"
android:thickness="15dp"
android:useLevel="true">
<solid android:color="#color/main_color" />
</shape>
</rotate>
</item>
<item android:bottom="211dp">
<shape
android:innerRadiusRatio="1000"
android:shape="ring"
android:thickness="7dp"
android:useLevel="false">
<solid android:color="#color/main_color" />
</shape>
</item>
<item>
<rotate>
<inset android:insetBottom="211dp">
<shape
android:innerRadiusRatio="1000"
android:shape="ring"
android:thickness="7dp"
android:useLevel="false">
<solid android:color="#color/main_color" />
</shape>
</inset>
</rotate>
</item>
</layer-list>
I don't have a secondary process here, but you should be able to adjust it for that as well.
A simple and efficient class extending View to draw circular progress, with rounded corners as an option. Progress color, background color, stroke width are also customizable. As seen in my other answer.
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.view.View
import androidx.annotation.FloatRange
class CircularProgressView : View {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
private val progressPaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.STROKE
}
private val backgroundPaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.STROKE
}
private val rect = RectF()
private val startAngle = -90f
private val maxAngle = 360f
private val maxProgress = 100
private var diameter = 0f
private var angle = 0f
override fun onDraw(canvas: Canvas) {
drawCircle(maxAngle, canvas, backgroundPaint)
drawCircle(angle, canvas, progressPaint)
}
override fun onSizeChanged(width: Int, height: Int, oldWidth: Int, oldHeight: Int) {
diameter = Math.min(width, height).toFloat()
updateRect()
}
private fun updateRect() {
val strokeWidth = backgroundPaint.strokeWidth
rect.set(strokeWidth, strokeWidth, diameter - strokeWidth, diameter - strokeWidth)
}
private fun drawCircle(angle: Float, canvas: Canvas, paint: Paint) {
canvas.drawArc(rect, startAngle, angle, false, paint)
}
private fun calculateAngle(progress: Float) = maxAngle / maxProgress * progress
fun setProgress(#FloatRange(from = 0.0, to = 100.0) progress: Float) {
angle = calculateAngle(progress)
invalidate()
}
fun setProgressColor(color: Int) {
progressPaint.color = color
invalidate()
}
fun setProgressBackgroundColor(color: Int) {
backgroundPaint.color = color
invalidate()
}
fun setProgressWidth(width: Float) {
progressPaint.strokeWidth = width
backgroundPaint.strokeWidth = width
updateRect()
invalidate()
}
fun setRounded(rounded: Boolean) {
progressPaint.strokeCap = if (rounded) Paint.Cap.ROUND else Paint.Cap.BUTT
invalidate()
}
}
you can add a circle/oval shape on the end & begin side of the ring, just like the below code
a layer-list drawable contain two circle/oval shape drawable and a ring shape drawable
round_progress_drawable.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:bottom="294px"
android:left="540px"
android:right="48px"
android:top="294px">
<shape
android:innerRadius="6px"
android:shape="oval">
<solid android:color="#FFFFFF"/>
</shape>
</item>
<item>
<shape
android:innerRadius="240px"
android:shape="ring"
android:thickness="12px">
<size
android:width="600px"
android:height="600px"/>
<solid android:color="#FFFFFF"/>
</shape>
</item>
<item>
<rotate>
<layer-list>
<item
android:bottom="294px"
android:left="540px"
android:right="48px"
android:top="294px">
<shape
android:innerRadius="6px"
android:shape="oval">
<solid android:color="#FFFFFF"/>
</shape>
</item>
</layer-list>
</rotate>
</item>
</layer-list>
round_progress_animation_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_window_focused="true">
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="5000"
android:propertyName="ImageLevel"
android:repeatCount="infinite"
android:valueFrom="0"
android:valueTo="10000"
android:valueType="intType">
</objectAnimator>
</item>
<item>
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="0"
android:propertyName="ImageLevel"
android:valueFrom="0"
android:valueTo="0"
android:valueType="intType">
</objectAnimator>
</item>
</selector>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimaryDark"
tools:context=".MainActivity">
<ImageView
android:stateListAnimator="#animator/round_progress_animation_selector"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/round_progress_drawable" />
</FrameLayout>
I tried to tackle this for arbitrary size progress bars and if you can ensure the progress bar is a square and you don't use margins, this should work but it doesn't. Android 10 renders it sometimes correctly sometime it doesn't. Especially progress values > 50% tend to break badly. It is not a working solution but might give someone an idea. There are still issues with the gradient fill. The end color doesn't match it. But if you use solid colors, it should work fine. Also the rounded cap causes the bar to show larger value range. My idea was to replace the ring with a shape that is 5dp x 2.5dp rectangle in background color with clipped half a circle. You would need to use different rotations for the start and end:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<rotate
android:fromDegrees="270"
android:toDegrees="270">
<shape
android:innerRadiusRatio="2.4"
android:shape="ring"
android:thickness="5dp"
android:useLevel="true"><!-- this line fixes the issue for lollipop api 21 -->
<gradient
android:angle="0"
android:endColor="#color/yellow"
android:startColor="#color/orange"
android:type="sweep"
android:useLevel="false" />
</shape>
</rotate>
</item>
<item
android:gravity="top">
<shape
android:innerRadiusRatio="1000"
android:shape="ring"
android:thickness="2.5dp"
android:useLevel="false">
<solid android:color="#color/orange" />
<size android:height="5dp"/>
</shape>
</item>
<item>
<rotate>
<scale android:scaleGravity="top|center_horizontal"
android:scaleHeight="150%"
android:scaleWidth="150%">
<shape
android:innerRadiusRatio="1000"
android:shape="ring"
android:thickness="2.5dp"
android:useLevel="false">
<solid android:color="#color/yellow" />
</shape>
</scale>
</rotate>
</item>
</layer-list>

How to make a view with rounded corners?

I am trying to make a view in android with rounded edges. The solution I found so far is to define a shape with rounded corners and use it as the background of that view.
Here is what I did, define a drawable as given below:
<padding
android:top="2dp"
android:bottom="2dp"/>
<corners android:bottomRightRadius="20dp"
android:bottomLeftRadius="20dp"
android:topLeftRadius="20dp"
android:topRightRadius="20dp"/>
Now I used this as the background for my layout as below:
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"
android:clipChildren="true"
android:background="#drawable/rounded_corner">
This works perfectly fine, I can see that the view has rounded edges.
But my layout has got many other child views in it, say an ImageView or a MapView. When I place an ImageView inside the above layout, the corners of image are not clipped/cropped, instead it appears full.
I have seen other workarounds to make it work like the one explained here.
But is there a method to set rounded corners for a view and all its
child views are contained within that main view that has rounded
corners?
Another approach is to make a custom layout class like the one below. This layout first draws its contents to an offscreen bitmap, masks the offscreen bitmap with a rounded rect and then draws the offscreen bitmap on the actual canvas.
I tried it and it seems to work (at least for my simple testcase). It will of course affect performance compared to a regular layout.
package com.example;
import android.content.Context;
import android.graphics.*;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.widget.FrameLayout;
public class RoundedCornerLayout extends FrameLayout {
private final static float CORNER_RADIUS = 40.0f;
private Bitmap maskBitmap;
private Paint paint, maskPaint;
private float cornerRadius;
public RoundedCornerLayout(Context context) {
super(context);
init(context, null, 0);
}
public RoundedCornerLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, 0);
}
public RoundedCornerLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs, defStyle);
}
private void init(Context context, AttributeSet attrs, int defStyle) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
cornerRadius = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, CORNER_RADIUS, metrics);
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
maskPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
maskPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
setWillNotDraw(false);
}
#Override
public void draw(Canvas canvas) {
Bitmap offscreenBitmap = Bitmap.createBitmap(canvas.getWidth(), canvas.getHeight(), Bitmap.Config.ARGB_8888);
Canvas offscreenCanvas = new Canvas(offscreenBitmap);
super.draw(offscreenCanvas);
if (maskBitmap == null) {
maskBitmap = createMask(canvas.getWidth(), canvas.getHeight());
}
offscreenCanvas.drawBitmap(maskBitmap, 0f, 0f, maskPaint);
canvas.drawBitmap(offscreenBitmap, 0f, 0f, paint);
}
private Bitmap createMask(int width, int height) {
Bitmap mask = Bitmap.createBitmap(width, height, Bitmap.Config.ALPHA_8);
Canvas canvas = new Canvas(mask);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.WHITE);
canvas.drawRect(0, 0, width, height, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
canvas.drawRoundRect(new RectF(0, 0, width, height), cornerRadius, cornerRadius, paint);
return mask;
}
}
Use this like a normal layout:
<com.example.RoundedCornerLayout
android:layout_width="200dp"
android:layout_height="200dp">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/test"/>
<View
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#ff0000"
/>
</com.example.RoundedCornerLayout>
Or you can use a android.support.v7.widget.CardView like so:
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
card_view:cardBackgroundColor="#color/white"
card_view:cardCornerRadius="4dp">
<!--YOUR CONTENT-->
</android.support.v7.widget.CardView>
shape.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#f6eef1" />
<stroke
android:width="2dp"
android:color="#000000" />
<padding
android:bottom="5dp"
android:left="5dp"
android:right="5dp"
android:top="5dp" />
<corners android:radius="5dp" />
</shape>
and inside you layout
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"
android:clipChildren="true"
android:background="#drawable/shape">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/your image"
android:background="#drawable/shape">
</LinearLayout>
Jaap van Hengstum's answer works great however I think it is expensive and if we apply this method on a Button for example, the touch effect is lost since the view is rendered as a bitmap.
For me the best method and the simplest one consists in applying a mask on the view, like that:
#Override
protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {
super.onSizeChanged(width, height, oldWidth, oldHeight);
float cornerRadius = <whatever_you_want>;
this.path = new Path();
this.path.addRoundRect(new RectF(0, 0, width, height), cornerRadius, cornerRadius, Path.Direction.CW);
}
#Override
protected void dispatchDraw(Canvas canvas) {
if (this.path != null) {
canvas.clipPath(this.path);
}
super.dispatchDraw(canvas);
}
Create a xml file called round.xml in the drawable folder and paste this content:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="#FFFFFF" />
<stroke android:width=".05dp" android:color="#d2d2d2" />
<corners android:topLeftRadius="5dp" android:topRightRadius="5dp" android:bottomRightRadius="5dp" android:bottomLeftRadius="5dp"/>
</shape>
then use the round.xml as background to any item. Then it will give you rounded corners.
If you are having problem while adding touch listeners to the layout. Use this layout as parent layout.
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.Region;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.widget.FrameLayout;
public class RoundedCornerLayout extends FrameLayout {
private final static float CORNER_RADIUS = 6.0f;
private float cornerRadius;
public RoundedCornerLayout(Context context) {
super(context);
init(context, null, 0);
}
public RoundedCornerLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, 0);
}
public RoundedCornerLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs, defStyle);
}
private void init(Context context, AttributeSet attrs, int defStyle) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
cornerRadius = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, CORNER_RADIUS, metrics);
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
#Override
protected void dispatchDraw(Canvas canvas) {
int count = canvas.save();
final Path path = new Path();
path.addRoundRect(new RectF(0, 0, canvas.getWidth(), canvas.getHeight()), cornerRadius, cornerRadius, Path.Direction.CW);
canvas.clipPath(path, Region.Op.REPLACE);
canvas.clipPath(path);
super.dispatchDraw(canvas);
canvas.restoreToCount(count);
}
}
as
<?xml version="1.0" encoding="utf-8"?>
<com.example.view.RoundedCornerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="#+id/patentItem"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingRight="20dp">
... your child goes here
</RelativeLayout>
</com.example.view.RoundedCornerLayout>
In case you want to round some specific corner.
fun setCorners() {
val mOutlineProvider = object : ViewOutlineProvider() {
override fun getOutline(view: View, outline: Outline) {
val left = 0
val top = 0;
val right = view.width
val bottom = view.height
val cornerRadiusDP = 16f
val cornerRadius = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, cornerRadiusDP, resources.displayMetrics).toInt()
// all corners
outline.setRoundRect(left, top, right, bottom, cornerRadius.toFloat())
/* top corners
outline.setRoundRect(left, top, right, bottom+cornerRadius, cornerRadius.toFloat())*/
/* bottom corners
outline.setRoundRect(left, top - cornerRadius, right, bottom, cornerRadius.toFloat())*/
/* left corners
outline.setRoundRect(left, top, right + cornerRadius, bottom, cornerRadius.toFloat())*/
/* right corners
outline.setRoundRect(left - cornerRadius, top, right, bottom, cornerRadius.toFloat())*/
/* top left corner
outline.setRoundRect(left , top, right+ cornerRadius, bottom + cornerRadius, cornerRadius.toFloat())*/
/* top right corner
outline.setRoundRect(left - cornerRadius , top, right, bottom + cornerRadius, cornerRadius.toFloat())*/
/* bottom left corner
outline.setRoundRect(left, top - cornerRadius, right + cornerRadius, bottom, cornerRadius.toFloat())*/
/* bottom right corner
outline.setRoundRect(left - cornerRadius, top - cornerRadius, right, bottom, cornerRadius.toFloat())*/
}
}
myView.apply {
outlineProvider = mOutlineProvider
clipToOutline = true
}
}
Can be used on a LinearLayout with children that looks like this:
to this:
With the Material Components Library the best way to make a View with rounded corners is to use the MaterialShapeDrawable.
Create a ShapeAppearanceModel with custom rounded corners:
ShapeAppearanceModel shapeAppearanceModelLL1 = new ShapeAppearanceModel()
.toBuilder()
.setAllCorners(CornerFamily.ROUNDED,radius16)
.build();
Create a MaterialShapeDrawable:
MaterialShapeDrawable shapeDrawableLL1 = new MaterialShapeDrawable(shapeAppearanceModeLL1);
If you want to apply also an elevationOverlay for the dark theme use this:
MaterialShapeDrawable shapeDrawableLL1 = MaterialShapeDrawable.createWithElevationOverlay(this, 4.0f);
shapeDrawableLL1.setShapeAppearanceModel(shapeAppearanceModelLL1);
Optional: apply to the shapeDrawable a background color and a stroke
shapeDrawableLL1.setFillColor(
ContextCompat.getColorStateList(this,R.color...));
shapeDrawableLL1.setStrokeWidth(2.0f);
shapeDrawableLL1.setStrokeColor(
ContextCompat.getColorStateList(this,R.color...));
Finally apply the shapeDrawable as background in your LinearLayout (or other view):
LinearLayout linearLayout1= findViewById(R.id.ll_1);
ViewCompat.setBackground(linearLayout1,shapeDrawableLL1);
In Android L you will be able to just use View.setClipToOutline to get that effect. In previous versions there is no way to just clip the contents of a random ViewGroup in a certain shape.
You will have to think of something that would give you a similar effect:
If you only need rounded corners in the ImageView, you can use a shader to 'paint' the image over the shape you are using as background. Take a look at this library for an example.
If you really need every children to be clipped, maybe you can another view over your layout? One with a background of whatever color you are using, and a round 'hole' in the middle? You could actually create a custom ViewGroup that draws that shape over every children overriding the onDraw method.
Create a xml file under your drawable folder with following code. (The name of the file I created is rounded_corner.xml)
rounded_corner.xml
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<!-- view background color -->
<solid
android:color="#a9c5ac" >
</solid>
<!-- view border color and width -->
<stroke
android:width="3dp"
android:color="#1c1b20" >
</stroke>
<!-- If you want to add some padding -->
<padding
android:left="4dp"
android:top="4dp"
android:right="4dp"
android:bottom="4dp" >
</padding>
<!-- Here is the corner radius -->
<corners
android:radius="10dp" >
</corners>
</shape>
And keep this drawable as background for the view to which you want to keep rounded corner border. Let’s keep it for a LinearLayout
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/rounded_corner"
android:layout_centerInParent="true">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hi, This layout has rounded corner borders ..."
android:gravity="center"
android:padding="5dp"/>
</LinearLayout>
The CardView worked for me in API 27 in Android Studio 3.0.1. The colorPrimary was referenced in the res/values/colors.xml file and is just an example. For the layout_width of 0dp it will stretch to the width of the parent. You'll have to configure the constraints and width/height to your needs.
<android.support.v7.widget.CardView
android:id="#+id/cardView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:cardCornerRadius="4dp"
app:cardBackgroundColor="#color/colorPrimary">
<!-- put your content here -->
</android.support.v7.widget.CardView>
You can use an androidx.cardview.widget.CardView like so:
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardCornerRadius="#dimen/dimen_4"
app:cardElevation="#dimen/dimen_4"
app:contentPadding="#dimen/dimen_10">
...
</androidx.cardview.widget.CardView>
OR
shape.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#f6eef1" />
<stroke
android:width="2dp"
android:color="#000000" />
<padding
android:bottom="5dp"
android:left="5dp"
android:right="5dp"
android:top="5dp" />
<corners android:radius="5dp" />
</shape>
and inside you layout
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/shape">
...
</LinearLayout>
To create round corner image using com.google.android.material:material:1.2.0-beta01
float radius = context.getResources().getDimension(R.dimen.border_radius_hug);
shapeAppearanceModel = new ShapeAppearanceModel()
.toBuilder()
.setAllCorners(CornerFamily.ROUNDED,radius)
.build();
imageView.setShapeAppearanceModel(shapeAppearanceModel)
or if you want to use it in xml file:
<com.google.android.material.imageview.ShapeableImageView
android:id="#+id/thumb"
android:layout_width="80dp"
android:layout_height="60dp"
app:shapeAppearanceOverlay="#style/circleImageView"
/>
in style.xml add this:
<style name="circleImageView" parent="">
<item name="cornerFamily">rounded</item>
<item name="cornerSize">10%</item>
</style>
follow this tutorial and all the discussion beneath it -
http://www.curious-creature.org/2012/12/11/android-recipe-1-image-with-rounded-corners/
according to this post written by Guy Romain, one of the leading developers of the entire Android UI toolkit, it is possible to make a container (and all his child views) with rounded corners, but he explained that it too expensive (from performances of rendering issues).
I'll recommend you to go according to his post, and if you want rounded corners, then implement rounded corners ImageView according to this post. then, you could place it inside a container with any background, and you'll get the affect you wish.
that's what I did also also eventually.
public class RoundedCornerLayout extends FrameLayout {
private double mCornerRadius;
public RoundedCornerLayout(Context context) {
this(context, null, 0);
}
public RoundedCornerLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RoundedCornerLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs, defStyle);
}
private void init(Context context, AttributeSet attrs, int defStyle) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
public double getCornerRadius() {
return mCornerRadius;
}
public void setCornerRadius(double cornerRadius) {
mCornerRadius = cornerRadius;
}
#Override
public void draw(Canvas canvas) {
int count = canvas.save();
final Path path = new Path();
path.addRoundRect(new RectF(0, 0, canvas.getWidth(), canvas.getHeight()), (float) mCornerRadius, (float) mCornerRadius, Path.Direction.CW);
canvas.clipPath(path, Region.Op.REPLACE);
canvas.clipPath(path);
super.draw(canvas);
canvas.restoreToCount(count);
}
}
Difference from Jaap van Hengstum's answer:
Use BitmapShader instead of mask bitmap.
Create bitmap only once.
public class RoundedFrameLayout extends FrameLayout {
private Bitmap mOffscreenBitmap;
private Canvas mOffscreenCanvas;
private BitmapShader mBitmapShader;
private Paint mPaint;
private RectF mRectF;
public RoundedFrameLayout(Context context) {
super(context);
init();
}
public RoundedFrameLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public RoundedFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
setWillNotDraw(false);
}
#Override
public void draw(Canvas canvas) {
if (mOffscreenBitmap == null) {
mOffscreenBitmap = Bitmap.createBitmap(canvas.getWidth(), canvas.getHeight(), Bitmap.Config.ARGB_8888);
mOffscreenCanvas = new Canvas(mOffscreenBitmap);
mBitmapShader = new BitmapShader(mOffscreenBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setShader(mBitmapShader);
mRectF = new RectF(0f, 0f, canvas.getWidth(), canvas.getHeight());
}
super.draw(mOffscreenCanvas);
canvas.drawRoundRect(mRectF, 8, 8, mPaint);
}
}
The tutorial link you provided seems to suggest that you need to set the layout_width and layout_height properties, of your child elements to match_parent.
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent">
try this property with your linear layout it will help
tools:context=".youractivity"
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels) {
Bitmap roundedBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap
.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(roundedBitmap);
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 roundedBitmap;
}
I have seen many solutions, but most of them are useless with Image
View unless you change Image View to other design components, and I do
not recommend them because they may not be compatible with some
**
solution using:
**
Width and color of stroke in drawable
And Margin for the picture
versions. Here is the quick solution.
The first step:
<RelativeLayout
android:layout_width="90dp"
android:layout_height="90dp">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:scaleType="centerCrop"
android:src="#drawable/a" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/card_helh" />
</RelativeLayout>
design shape
The second step:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="#dimen/_10dp"/>
<stroke android:color="#color/white" android:width="5dp"/>
</shape>
**
A note
** about setting the night mode, set the color stroke color to the color of the container's night so that it appears more homogeneous This
solution works 100%
This solution is mine and I am currently using it
Use shape in xml with rectangle.set the property of bottom or upper radius as want.then apply that xml as background to ur view....or...use gradients to do it from code.

Create an Incomplete Button Stroke

Aim: Stroke only the top and bottom.
What I've tried:
Below is a copy of my XML.
I've tried following the solution in This Stack Overflow Answer.
But my problem is that the doesn't let me choose the options of cutting off the left and right by 1dp as per the solution.
Any ideas?
Code:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<shape >
<gradient
android:startColor="#color/secondaryButtonStartColorSelected"
android:endColor="#color/secondaryButtonEndColorSelected"
android:angle="270" />
<stroke
android:width="#dimen/secondary_button_border_size"
android:color="#color/secondaryButtonBorderColorSelected" />
</shape>
</item>
<item android:state_focused="true" >
<shape>
<gradient
android:startColor="#color/secondaryButtonStartColorSelected"
android:endColor="#color/secondaryButtonEndColorSelected"
android:angle="270" />
<stroke
android:width="#dimen/secondary_button_border_size"
android:color="#color/secondaryButtonBorderColorSelected"/>
</shape>
</item>
</selector>
You could create a custom Drawable to handle this for you, but you'd have to set it in code vs XML. Here's a quick and dirty version:
public class HorizontalStrokeDrawable extends Drawable {
private Paint mPaint = new Paint();
private int mStrokeWidth;
public HorizontalStrokeDrawable (int strokeColor, int strokeWidth) {
mPaint.setColor(strokeColor);
mStrokeWidth = strokeWidth;
}
#Override
public void draw (Canvas canvas) {
Rect bounds = getBounds();
canvas.drawRect(0, 0, bounds.right, mStrokeWidth, mPaint);
canvas.drawRect(0, bounds.bottom - mStrokeWidth, bounds.right, bounds.bottom, mPaint);
}
#Override
public void setAlpha (int alpha) {
mPaint.setAlpha(alpha);
invalidateSelf();
}
#Override
public void setColorFilter (ColorFilter cf) {
mPaint.setColorFilter(cf);
invalidateSelf();
}
#Override
public int getOpacity () {
return PixelFormat.TRANSLUCENT;
}
}
Now you can just set it wherever you need it:
view.setBackgroundDrawable(new HorizontalStrokeDrawable(myColor, myStrokeWidth));

Categories

Resources