Android canvas rounded rectangle

How to draw a path with rounded corners

I should draw a CustomView like this shot.

but they are not the same. corner strokes are different.

I use 2 separated Path to draw the top shape: first one for yellow background:

and the second is:

and in onDraw() function I draw by them:

Update: now I drew this that has 2 sides for its pointer.

and used this path to draw:

2 Answers 2

Canvas has some pre-defined methods for drawing common shapes like circle and rectangle. In your scenario, you can use drawRoundRect which needs a RectF to draw a rectangle.

Here is an example:

BTW, If you want to draw rounded corners using a path, you must set pathEffect with CornerPathEffect .

Here is an example:

I think I got a solution for you

It took me quite some time to figure out what’s happening there.

Note that my solution draws only a rounded rectangle without using path, but instead drawRoundRect pre-defined method of Canvas .

I was creating a custom progress bar which would have a border/stroke. The first thing came to my mind was to create a Paint instance, set the style of the paint to Paint.Style.STROKE and then draw a rounded rectangle.

Note: The code above draws only the stroke, if you wanna draw the progress inside as well, you can create a new rect and set the style of the paint Paint.Style.FILL . It should be pretty straightforward to do it.

Well, this is what I get when I draw the progress stroke by using the code above, which does not look nice.

First I thought that the corners are not properly drawn and I should maybe increase the corner radius, but that was not a solution. After doing some research and testing different implementations I figured out that the issue is not related to the corners but the view itself. My stroke was just cut and not fully visible.

Adding insets was the key to solving my issue and it was pretty straightforward to do it.

This is the modified code:

I’ve added a single line only which sets the insets to half of the stroke width, which was the exact size which was cut.

I’ve also modified the strokeWidth a bit for it to look nice ( 2f instead of 4f ). You can change it later to match your design requirements.

After that voila, you have the stroke which you would expect to have.

I hope my solution will help you save time and energy!

Источник

Rounded Rectangle with Android Canvas

I’m attempting to draw a rectangle around a custom view in Android. I mostly have it working except for one detail.

Here is my code.

And here is the resulting rectangle.

As you can see, the inside of the rectangle does have rounded corners, but the outside still draws pointed corners. How can I make it so that the outside corners are rounded as well?

Читайте также:  Лучшие офлайн читалки для андроид

1 Answer 1

You don’t see corners rounded on the outside because part of the stroke is outside of the bounds of the Canvas . You can check this easily by adding a certain margin to the coordinates of the round rectangle to make sure it is drawn inside the Canvas .

In fact your best option is trying to optimize this margin depending on the selected stroke width.

Not the answer you’re looking for? Browse other questions tagged android canvas or ask your own question.

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.12.3.40888

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Draw rounded rectangle using RectF and canvas?

I’m attempting to draw a rounded rectangle using RectF and canvas.drawRoundRect(). Please see my code below:

The program runs but nothing gets drawn i.e. I just get my white background screen. Any ideas as to why?

Note: I’m creating my relative layout programatically as opposed to using XML for scaling purposes.

4 Answers 4

Actually here your RectF representing Point not Rectangle , that’s why you are unable to see Rect .

and here RectF is

here left = right = 200 and top = bottom = 400 which represents a Point

if you want to draw a Rect of width = 200 and height = 400 , then your RectF should be

and for width = 400 and height = 200 , RectF should be

You have not created proper rectangle. Give your rectangle proper left ,top, right, bottom points like: RectF rectf = new RectF(0, 0, 480, 854);

Cheers guys. Spot on. I’ve corrected my code as seen below and now I can see my rectangle.

RectF holds four float coordinates for a rectangle. The rectangle is represented by the coordinates of its 4 edges (left, top, right bottom).

In the snippet, the RectF Arguments as the docs say represents the edges coordinates of the Rectangle.

As a conclusion,
width = | left — right |
height = | top — bottom |

If the width and height were 0 as in the question it would not represent a view nor an object,
which in logic is impossible for an object to exist of the height, width and depth of 0.

Источник

How to use android canvas to draw a Rectangle with only topleft and topright corners round?

I found a function for rectangles with all 4 corners being round, but I want to have just the top 2 corners round. What can I do?

16 Answers 16

Use a path. It has the advantage of working for APIs less than 21 (Arc is also limited thusly, which is why I quad). Which is a problem because not everybody has Lollipop yet. You can however specify a RectF and set the values with that and use arc back to API 1, but then you wouldn’t get to use a static (without declaring a new object to build the object).

Drawing a rounded rect:

Читайте также:  Автокад для андроид крякнутый

As a full function:

You’d want to line all the way to those corner bits, rather than quad across them. This is what setting true to conformToOriginalPost does. Just line to the control point there.

If you want to do that all but don’t care about pre-Lollipop stuff, and urgently insist that if your rx and ry are high enough, it should draw a circle.

So, conformToOriginalPost actually draws a rounded rect without the bottom two bits rounded.

I would draw two rectangles:

Or something like that, you just overlap them so that the upper corners will be round. Preferably you should write a method for this

For API 21 and above the Path class added a new method addRoundRect() which you can use it like this.

I changed this answer so you can set which corner you want to be round and which one you want to be sharp. also works on pre-lolipop

Usage Example:

only top-right and botton-right corners are rounded

RoundRect:

Simple helper function written in Kotlin.

Usage:

you can easily achieve this by using Path:

I achieved this by following the below steps.

These are the pre-requisites for the rounded rectangle to look neat

  • The radius of the edges have to be equal to the (height of the rectangle / 2). This is because if its any different value then the place where the curve meets straight line of the rectangle will not be

Next is the steps to draw the rounded rectangle.

First we draw 2 circles on the left and right side, with the radius = height of rectange / 2

Then we draw a rectangle between these circles to get the desired rounded rectangle.

I am posting the code below

Now this results in a really nice rounded rectangle like the one shown below

This is an old question, however I wanted to add my solution because it uses the native SDK without lots of custom code or hacky drawing. This solution is supported back to API 1.

The way to do this properly is to create a path (as mentioned in other answers) however the previous answers seem to overlook the addRoundedRect function call that takes radii for each corner.

Variables

Setup Paint

Update Path with Size Changes

Call this somewhere that isn’t onDraw, such as onMeasure for a view or onBoundChange for a drawable. If it doesn’t change (like this example) you could put this code where you set up your paint.

This code creates a 100×100 rounded rect with the top corners rounded with a 25 radius.

Draw Path

Call this in onDraw for a view or draw for a drawable.

One simple and efficient way to draw a solid side is to use clipping — rect clipping is essentially free, and a lot less code to write than a custom Path.

If I want a 300×300 rect, with the top left and right rounded by 50 pixels, you can do:

This approach will only work for rounding on 2 or 3 adjacent corners, so it’s a little less configurable than a Path based approach, but using round rects is more efficient, since drawRoundRect() is fully hardware accelerated (that is, tessellated into triangles) while drawPath() always falls back to software rendering (software-draw a path bitmap, and upload that to be cached on the GPU).

Читайте также:  Проверка штрих кода андроидом

Not a huge performance issue for small infrequent drawing, but if you’re animating paths, the cost of software draw can make your frame times longer, and increase your chance to drop frames. The path mask also costs memory.

If you do want to go with a Path-based approach, I’d recommend using GradientDrawable to simplify the lines of code (assuming you don’t need to set a custom shader, e.g. to draw a Bitmap).

With GradientDrawable#setCornerRadii(), you can set any corner to be any roundedness, and reasonably animate between states.

Источник

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

Источник

Оцените статью