- How to Make Rounded Corners(Boarder Radius) of ImageView in Android
- Android Example: Make an ImageView Image Rounded Corners in Android
- Download Complete Example Project
- Drawing a rounded corner background on text
- To span or not to span? This is the question!
- Solution: custom TextView
- Finding out where the background should be drawn
- Provide drawables as attributes
- Render the background drawable(s)
- Supporting custom drawing on a TextView
- Add Rounded Corners to Views and Layouts Android
- Rounded Corners
- Rounded Border with Transparent Inside
- Applying the border to a Layout or View
- Rounded Border with Coloured Inside
- Less rounded Corner
- Set Background Programatically
- Bonus
- Dynamic Square & Rectangular layouts in Android
- Change StatusBar Color in Android Lollipop and Above
- Set Custom font for TextView and EditText in Android using fontFamily
- 4 Responses
- Android Canvas: создание объекта RoundRectShape
- 3 ответа
- aprock / RoundedTransformation.java
- This comment has been minimized.
- JakeWharton commented Jul 8, 2014
- This comment has been minimized.
- broakenmedia commented Jul 17, 2014
- This comment has been minimized.
- Naderkunbhar commented Sep 15, 2014
- This comment has been minimized.
- Naderkunbhar commented Sep 15, 2014
- This comment has been minimized.
- miao1007 commented Oct 5, 2014
- This comment has been minimized.
- rsablania commented Oct 27, 2014
- This comment has been minimized.
- ashokcs commented Jan 7, 2015
- This comment has been minimized.
- cbeyls commented Jul 29, 2015
- This comment has been minimized.
- crackcode007 commented Nov 3, 2015
- This comment has been minimized.
- Mark-Mark-Mark commented Jan 6, 2016
- This comment has been minimized.
- abdul-martinez commented Apr 21, 2016
- This comment has been minimized.
- hossain-khan commented Jul 25, 2016 •
- This comment has been minimized.
- mensly commented Feb 9, 2017
How to Make Rounded Corners(Boarder Radius) of ImageView in Android
How to Make Roundness in the Corners(Boarder Radius) in an Image of ImageView in Android. In this tutorial, you will learn to make an ImageView rounded corner using java code. By default in android ImageView don’t have option to make corners rounded(border radius). But if you need corner radius, you can make it by different ways. Follow following example step by step to make rounded corner of ImageView images.
Android Example: Make an ImageView Image Rounded Corners in Android
XML Layout File
Following is the simple android xml layout with a LinearLayout and an ImageView. This ImageView has an id image_view.
res/layout/activity_main.xml
Java Activity File
Following is the java code to make ImageView image corner rounded(border radius) . Following is the final code of MainActivity.java file.
src/MainActivity.java
Following is the default strings of strings.xml file.
res/values/strings.xml
Following is also the default content of AndroidManifest.xml file.
After running your application the output looks like below:
Output:
Android ImageView Rounded Corners(Boarder Radius) |
Download Complete Example Project
Download complete How to Make Roundness in the Corners(Boarder Radius) in an Image of ImageView in Android project source code from GitHub.
Источник
Drawing a rounded corner background on text
Let’s say that we need to draw a rounded corner background on text, supporting the following cases:
- Set the background on one line text
How can we implement this? Read on to find out, or jump directly to the sample code.
To span or not to span? This is the question!
In previous articles we’ve covered styling sections of text (even internationalized text). The solution involved using either framework or custom spans. While spans are a great solution in many cases, they do have some limitations that make them unsuitable for our problem. Appearance spans, like BackgroundColorSpan , give us access to the TextPaint , allowing us to change elements like the background color of text, but are only able to draw a solid color and can’t control elements like the corner radius.
We need to draw a drawable together with the text. We can implement a custom ReplacementSpan to draw the background and the text ourselves. However ReplacementSpans cannot flow into the next line, therefore we will not be able to support a multi-line background. They would rather look like Chip, the Material Design component, where every element must fit on a single line.
Spans work at the TextPaint level, not the layout level. Therefore, they can’t know about the line number the text starts and ends on, or about the paragraph direction (left-to-right or right-to-left)
Solution: custom TextView
Depending on the position of the text, we need to draw four different drawables as text backgrounds:
- Text fits on one line: we only need one drawable
- Text fits on 2 lines: we need drawables for the start and end of the text
- Text spans multiple lines: we need drawables for the start, middle and end of the text.
To position the background, we need to:
- Determine whether the text spans multiple lines
- Find the start and end lines
- Find the start and end offset depending on the paragraph direction
All of these can be computed based on the text Layout. To render the background behind the text we need access to the Canvas . A custom TextView has access to all of the information necessary to position the drawables and render them.
Our solution involves splitting our problem into 4 parts and creating classes dealing with them individually:
- Marking the position of the background is done in the XML resources with Annotation spans and then, in the code, we compute the positions in the TextRoundedBgHelper
- Providing the background drawables as attributes of the TextView — implemented in TextRoundedBgAttributeReader
- Rendering the drawables depending on whether the text runs across one or multiple lines — TextRoundedBgRenderer interface and its implementations: SingleLineRenderer and MultiLineRenderer
- Supporting custom drawing on a TextView — RoundedBgTextView , a class that extends AppCompatTextView , reads the attributes with the help of TextRoundedBgAttributeReader , overrides onDraw where it uses TextRoundedBgHelper to draw the background.
Finding out where the background should be drawn
We specify parts of the text that should have a background by using Annotation spans in our string resources. Find out more about working with Annotation spans from this article.
We created a TextRoundedBgHelper class that:
- Enables us to position the background based on the text directionality: left-to-right or right-to-left
- Renders the background, based on the drawables and the horizontal and vertical padding
In the TextRoundedBgHelper.draw method, for every Annotation span found in the text, we get the start and end index of the span, find the line number for each and then compute the start and end character offset (within the line). Then, we use the TextRoundedBgRenderer implementations to render the background.
Provide drawables as attributes
To easily supply drawables for different TextViews in our app, we define 4 custom attributes corresponding to the drawables and 2 attributes for the horizontal and vertical padding. We created a TextRoundedBgAttributeReader class that reads these attributes from the xml layout.
Render the background drawable(s)
Once we have the drawables we need to draw them. For that, we need to know:
- The start and end line for the background
- The character offset where the background should start and end at.
We created an abstract class TextRoundedBgRenderer that knows how to compute the top and the bottom offset of the line, but exposes an abstract draw function:
The draw function will have different implementations depending on whether our text spans a single line or multiple lines. Both of the implementations work on the same principle: based on the line top and bottom, set the bounds of the drawable and render it on the canvas.
The single line implementation only needs to draw one drawable.
The multi-line implementation needs to draw the start and the end of line drawables on the first, and last line respectively, then for each line in the middle, draw the middle line drawable.
Supporting custom drawing on a TextView
We extend AppCompatTextView and override onDraw to call TextRoundedBgHelper.draw before letting the TextView draw the text.
Caveat: Our sample makes all the calculations for every TextView.onDraw method call. If you’re planning on integrating this implementation in your app, we strongly suggest to modify it and cache the calculations done in TextRoundedBgHelper . Then, make sure you invalidate the cache whenever anything related to text, like text color, size or other properties, has changed.
The Android text APIs allow you a great deal of freedom to perform styling. Simple styling is possible with text attributes, styles, themes and spans. Complex custom styling is achievable by taking control of the onDraw method and making decisions on what and how to draw on the Canvas . Check out our sample for all implementation details.
What kind of text styling did you have to do that required custom TextView implementations? What kind of issues did you encounter? Tell us in the comments!
Источник
Add Rounded Corners to Views and Layouts Android
by Anu S Pillai · Published April 23, 2017 · Updated July 6, 2019
Rounded Corners
In this quick article we will see how to add Rounded corners to Views and Layouts. This can be done on Layout XML or Programatically. Here we will see both the ways.
Rounded Border with Transparent Inside
Create an xml inside Drawable Folder with below code. Name it rounded_red_border.xml
Applying the border to a Layout or View
Set the above drawable as a background to your Layout or View like LinearLayout, FrameLayout, TextView, Button etc.
Below are few more styles and examples.
Rounded Border with Coloured Inside
Less rounded Corner
To make it less rounded just reduce the corner radius value.
Set Background Programatically
Bonus
Creating a Button Selector (which changes colour on press) with Rounded Corners. Create an xml rounded_button_selector.xml in the Drawable Folder. Paste the below code and apply it as the Button Background.
In the above code, the Button changes colour to Green when pressed. You may add more states like enabled, focused etc.
Hope this quick tutorial is helpful for you.
Let me know your Suggestions / Queries in comments.
Follow GadgetSaint on Facebook / Twitter for updates.
The Admin at GadgetSaint.com
- Next story Dynamic Square & Rectangular layouts in Android
- Previous story Create a simple ViewPager Tabs in Android
Dynamic Square & Rectangular layouts in Android
by Anu S Pillai · Published May 11, 2017
Change StatusBar Color in Android Lollipop and Above
by Anu S Pillai · Published April 12, 2017 · Last modified April 17, 2017
Set Custom font for TextView and EditText in Android using fontFamily
October 29, 2019
by Anu S Pillai · Published October 29, 2019
4 Responses
why transparent button still has grey square inside?
Can you post a preview image with your code for drawable and view
Would it be possible to select only some of the corners to be rounded, and leave the other ones alone?
Источник
Android Canvas: создание объекта RoundRectShape
Я создал класс для прямоугольной формы, так как это объект в моем приложении. Однако теперь я бы хотел, чтобы углы были скруглены. Ниже вы можете видеть, что это простой класс, создающий столько прямоугольников, сколько мне нужно, с одинаковыми атрибутами.
Обновление: без этого метода у меня ничего не будет нарисовано, так как нет размера. При этом он рисует только обычный прямоугольник. (Целочисленные значения были изменены, чтобы не показывать методы, специфичные для приложения)
Из моего исследования я обнаружил, что я не могу просто добавить закругленные углы, а вместо этого должен создать RoundRectShape shapeDrawable . Каждая попытка создать прямоугольник со скругленными углами, используя это RoundRectShape , провалилась. Каким-то образом фигура всегда представляет собой правильный прямоугольник без закругленных углов.
Я ищу класс просто костей (как тот, который предоставляется), который создает рисование roundRectShape. Высота и ширина не имеют значения, если они имеют закругленные углы. Должно быть на Java, а не на XML.
Ссылки, которые я пробовал для создания круглых прямоугольников:
3 ответа
Я создал класс MyRect , который используется для рисования округленного Rect для вас.
Создание объектов выше MyRect недостаточно, нам нужно хранить ссылки на объекты в любом контейнере, чтобы мы могли изменить или удалить этот объект в будущем.
Внутри onDraw(Canvas canvas) метода View / SurfaceView вызовите метод MyRect draw() .
Готово, создать объект и добавить в контейнер.
Вы также можете расширить MyRect , например, добавить еще конструктор, метод и элемент данных в соответствии с вашими требованиями.
Почему бы вам не использовать функцию drawRoundRect класса Canvas ? открытый класс RoundRect < int l, r, t, b, rx, ry; Краска краска;
Пользовательская графика
Вы можете создавать собственные рисования, расширяя класс рисования
Шаги по созданию пользовательского Drawable
1. Подкласс Drawable и реализовать следующие методы методами
- public void draw(@NonNull Canvas canvas) — Вы получите объект холста для рисования фигур. Вызовите метод getBounds (), чтобы получить размеры в соответствии с представлением, в котором мы применили объект рисования.
- public void setAlpha(@IntRange(from = 0, to = 255) int alpha) — здесь вы получите целочисленное значение альфа, установите его в качестве основной краски, в которой вы рисуете фигуру.
- public void setColorFilter(@Nullable ColorFilter colorFilter) — здесь вы получите объект ColorFilter, установите его в качестве основной краски, в которой вы рисуете фигуру.
- public int getOpacity() — возвращает здесь значение непрозрачности, например PixelFormat.TRANSLUCENT, PixelFormat.TRANSPARENT, PixelFormat.RGB_888 и т. Д.
2. В onDraw() вызовите метод canvas.drawRoundRect () для рисования фигуры.
public void drawRoundRect(@android.support.annotation.NonNull android.graphics.RectF rect,float rx,float ry,@android.support.annotation.NonNull android.graphics.Paint paint)
Нарисуйте указанный круглый прямоугольник, используя указанную краску. Круглый будет заполнено или оформлено на основе стиля в краске.
1) rect — прямоугольные границы roundRect для рисования 2) rx — радиус овала овала, используемый для скругления углов 3) ry — Y-радиус овала, используемого для скругления углов 4) краска — краска, используемая для рисования roundRect
Источник
aprock / RoundedTransformation.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
import android.graphics.Bitmap ; |
import android.graphics.Bitmap.Config ; |
import android.graphics.BitmapShader ; |
import android.graphics.Canvas ; |
import android.graphics.Paint ; |
import android.graphics.RectF ; |
import android.graphics.Shader ; |
// enables hardware accelerated rounded corners |
// original idea here : http://www.curious-creature.org/2012/12/11/android-recipe-1-image-with-rounded-corners/ |
public class RoundedTransformation implements com.squareup.picasso . Transformation < |
private final int radius; |
private final int margin; // dp |
// radius is corner radii in dp |
// margin is the board in dp |
public RoundedTransformation ( final int radius , final int margin ) < |
this . radius = radius; |
this . margin = margin; |
> |
@Override |
public Bitmap transform ( final Bitmap source ) < |
final Paint paint = new Paint (); |
paint . setAntiAlias( true ); |
paint . setShader( new BitmapShader (source, Shader . TileMode . CLAMP , Shader . TileMode . CLAMP )); |
Bitmap output = Bitmap . createBitmap(source . getWidth(), source . getHeight(), Config . ARGB_8888 ); |
Canvas canvas = new Canvas (output); |
canvas . drawRoundRect( new RectF (margin, margin, source . getWidth() — margin, source . getHeight() — margin), radius, radius, paint); |
if (source != output) < |
source . recycle(); |
> |
return output; |
> |
@Override |
public String key () < |
return » rounded » ; |
> |
> |
This comment has been minimized.
Copy link Quote reply
JakeWharton commented Jul 8, 2014
Keys must be unique for a configuration of a transformation!
Even better if you pre-compute this string once in the constructor.
This comment has been minimized.
Copy link Quote reply
broakenmedia commented Jul 17, 2014
And what happens if you dont set it? Surely it’s not unique the radius and margin as it’s often the same for every image?
This comment has been minimized.
Copy link Quote reply
Naderkunbhar commented Sep 15, 2014
Android picasso in Gridview Adaptor Transformer is not applying,please tell me what is problem
package com.example.picasso_transform;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Typeface;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
///Nader
public class Adopter_Feeds extends BaseAdapter <
ArrayList data;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
public class Round_Corners implements Transformation <
private int Round;
This comment has been minimized.
Copy link Quote reply
Naderkunbhar commented Sep 15, 2014
is ther any problem in my code
This comment has been minimized.
Copy link Quote reply
miao1007 commented Oct 5, 2014
thanks,.work fine on my listview
This comment has been minimized.
Copy link Quote reply
rsablania commented Oct 27, 2014
Only rounds the upper 2 corners of my imageview @Naderkunbhar
This comment has been minimized.
Copy link Quote reply
ashokcs commented Jan 7, 2015
Getting exception when trying to make round transformation of 102 X 103 pix resolution image.
Please help me with this.
java.lang.RuntimeException: Transformation rounded(radius=0, margin=0) crashed with exception.
at com.squareup.picasso.BitmapHunter$3.run(BitmapHunter.java:370)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5356)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.graphics.Bitmap.createBitmap(Bitmap.java:903)
at android.graphics.Bitmap.createBitmap(Bitmap.java:880)
at android.graphics.Bitmap.createBitmap(Bitmap.java:847)
at com.company.app.ui.RoundedTransformation.transform(RoundedTransformation.java:45)
at com.squareup.picasso.BitmapHunter.applyCustomTransformations(BitmapHunter.java:365)
at com.squareup.picasso.BitmapHunter.hunt(BitmapHunter.java:174)
at com.squareup.picasso.BitmapHunter.run(BitmapHunter.java:111)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
at com.squareup.picasso.Utils$PicassoThread.run(Utils.java:408)
This comment has been minimized.
Copy link Quote reply
cbeyls commented Jul 29, 2015
Source is always different from output. Otherwise this code would not even work.
This comment has been minimized.
Copy link Quote reply
crackcode007 commented Nov 3, 2015
its working only with wrap_content image view not with given height and width
This comment has been minimized.
Copy link Quote reply
Mark-Mark-Mark commented Jan 6, 2016
@ashokcs where you able to solve your crash?
I’m having the same problem:
This comment has been minimized.
Copy link Quote reply
abdul-martinez commented Apr 21, 2016
@1492Mark @ashokcs have you solved this crash? I’m having crashes with the same @1492Mark stack trace.
This comment has been minimized.
Copy link Quote reply
hossain-khan commented Jul 25, 2016 •
If anybody is looking for option to apply rounded corner to only top and bottom corners individually, check following gist
This comment has been minimized.
Copy link Quote reply
mensly commented Feb 9, 2017
Thanks for this! Here’s my slight modification to convert to Kotlin and have appropriate defaults without needing to know the radius beforehand. Used to show pretty images in push notifications!
Источник