Как закруглить imageview
Перейти к содержимому

Как закруглить imageview

  • автор:

How to Make an Imageview With Rounded Corners

This is pretty late in response, but for anyone else that is looking for this, you can do the following code to manually round the corners of your images.

This isn’t my code, but I’ve used it and it’s works wonderfully. I used it as a helper within an ImageHelper class and extended it just a bit to pass in the amount of feathering I need for a given image.

Final code looks like this:

How to make an ImageView with rounded corners?

This is pretty late in response, but for anyone else that is looking for this, you can do the following code to manually round the corners of your images.

This isn’t my code, but I’ve used it and it’s works wonderfully. I used it as a helper within an ImageHelper class and extended it just a bit to pass in the amount of feathering I need for a given image.

Final code looks like this:

Imageview not showing rounded corners

Just use the ShapeableImageView in the Material Components library.

Sample Image

*Note: it requires at least the version 1.2.0-alpha03 .

How to quickly make ImageViews with rounded corners?

The solution is pretty simple actually, but yet hasn’t been suggested that much.
A few months ago I was searching for a simple solution to get a rounded ImageView, and all I could be able to find was complicated solutions.
I’m writing this answer, since this is not known by everybody (and this solution has been implemented in Android at the end of 2020), so that if someone new to Android Studio will have the same question will be able to quickly find a simple solution to make any ImageView rounded.

First thing first, since the solution is implemented in an androidx library, you should make sure that you’re declaring this dependency in your gradle:

After syncing your gradle, you will be able to use a component called "ImageFilterView".

ImageFilterView is sub-class of ImageView, so it inherits everything from a common ImageView, but there are a few things added in order to manipulate the image.
Among these new things, there is the attribute "roundPercent" which allows you to set how much the corners of the image should be rounded.
Remember that this is a percentage value, so it must be a float between 0.0 and 1.0 included.
Settings this attribute to 1.0 will make the image totally circular.

That’s all, nothing else to do, this will be enough to get a rounded ImageView:

(Remember that you have to define the "app" namespace at the beginning of the first layout of your xml file in order to be able to use it:

Rounded corner image view with a custom view

First of all, you are not drawing on the view ‘s canvas, you’ve to override onDraw to draw anything on the view ‘s canvas. And, as you just want to make your image circular from the corners, you don’t need PorterDuff for this. You can just clip a rounded rect from the canvas and it would be suffice for your use case.

You don’t have to manually override each constructor of the AppCompatImageView , You can use the @JvmOverloads annotation to override every constructor of the java class in kotlin .

Use withStyledAttributes extension function of core-ktx to access attributeSet

init block can be used to execute code just after the primary constructor .

Don’t do object allocation inside of onDraw , reuse expensive objects like paint and path as much as possible.

Keeping above points in mind, your class can be changed like this

Now, it can be used like this

ImageView with only bottom or top corners rounded

Here is the another way to do this using Material Design ShapeableImageView

Create one theme for shape and cornerFamily

Now add ShapeableImageView in XML:

I you want to full rounded ShapeableImageView:

Full Rounded Output:

Sample Image

That’s it Happy Coding :).

ImageView rounded corners

I use Universal Image loader library to download and round the corners of image, and it worked for me.

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Easy to use, lightweight custom image view with rounded corners.

mmmelik/RoundedImageView

Name already in use

  • Local
  • Codespaces

Use Git or checkout with SVN using the web URL.

Work fast with our official CLI. Learn more about the CLI.

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Easy to use, lightweight custom image view with rounded corners.
Explore the docs »

About The Project

Product Name Screen Shot

This library allows you to create ImageViews with soft edges that are pleasing to the eye.

To make this view running on your app follow these simple steps.

1. Add the JitPack repository to your project level build.gradle file

2. Add the dependency to your module level build.gradle file

RoundedImageView extends ImageView so all functions of ImageView are available for RoundedImageView .

In RoundedImageView XML attribute android:adjustViewBounds set to true by default. If it cause unintended behaviour of the view override with android:adjustViewBounds=»false» .

RoundedImageView does not manipulate drawable of the view. Only clips out the corners of the view. So make sure you have fully wrapped drawable with the views borders.

See the open issues for a list of proposed features (and known issues).

Contributions are what make the open source community such an amazing place to be learn, inspire, and create. Any contributions you make are greatly appreciated.

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:

How to Make Rounded Corners(Boarder Radius) in an Image of ImageView in Android
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.

How to make a Circular Image View in Android without Third-Party Library

In this tutorial, we are going to see how to create a circular image view and a circular image view with border-color in Android. Most of the time the android developers use a third-party library for creating a circular profile image, but this tutorial will explain how to create a circular image view without the help of the third-party library and plugins as well.

Most of the time the usage of third-party libraries degrade the speed and affect the data in an android application.

One of the most common tasks in android is to create a Circular ImageView. The default ImageView in android is rectangle so there are situations where we will have to create a circular ImageView.

There are different ways to achieve this but before that let us see the result of what we have to achieve. The image below represents the circular image view in the android application.

Steps:

1. Adding Support Library

You need to add the following support libraries to Gradle (Module.app) for CardView to work on your project.

Picasso and glide libraries are used for loading the image from the browser or server. Here, we use these libraries following.

2. Creating Circular ImageView without border-color

We have to create an empty activity and name it as activity_main.xml and MainActivity.java for our future use. In this stage, XML acts as a major role in creating a circular ImageView. You can define the XML code as follows…

activity_main.xml

You have to put your ImageView inside the CardView because CardView only has a feature of accessing the corner radius attribute. This corner radius attribute helps us to create a rounded ImageView. If you forget to do the below step, your image won't look circular. It will either look like a rectangle or rectangle with a corner radius.

IMPORTANT NOTE: CardView app:cardCornerRadius will double half of your CardView width and height. app:cardCornerRadius always depends on the height and width attribute of the CardView.

3. Creating Circular ImageView with border-color

  • Create drawable.xml for circular shape with border-color
  • Rewrite activity_main.xml for border-color
Create drawable.xml for circular shape with border-color

You have to create the cicular_bordershape.xml under the drawable folder. It will set the border color for the ImageView. You can define the XML code as follows…

circular_bordershape.xml

IMPORTANT NOTE: <stroke> is used to set the border width and as well as the border color.

Rewrite activity_main.xml for border-color

This is how you rewrite the activity_main.xml code for border-color. You can define the XML code as follows…

activity_main.xml

The CardView should be placed inside the RelativeLayout. We use this RelativeLayout to apply the background as drawable.xml for border-color, it gives your ImageView with border-color.

IMPORTANT NOTE:

RelativeLayout height and width calculation formula:-

(dp- Density independent pixels)

4. Load the image using Glide and Picasso tool

As mentioned above, Glide and Picasso libraries are used for loading the images from the server or browser. That's why we use these libraries for image loading. Custom view also loads the image from the server.

MainActivity.java

This brings us to the end of the blog post. I hope you have learned about creating circular imageview with a border for your android application. Now, you can run this on your android device and see the output for yourself.

Last updated: July 27th, 2023 at 9:47:46 AM GMT+0

Hellonext is a user feedback tool and this article was written by many people at Hellonext. Hellonext helps prioritize product roadmap based on user-input.

CircularImageview

This project allowing you to create circular and rounded corner Imageview in android through simplest way.

circularimageview

CircularImageview

This project allowing you to create circular and rounded corner imageview in android through simplest way.

In circular imageview It uses a BitmapShader and does not:

  • create a copy of the original bitmap
  • use a clipPath (which is neither hardware accelerated nor anti-aliased)
  • use setXfermode to clip the bitmap (which means drawing twice to the canvas)

USAGE

To make a circular ImageView add CircularImageView in your layout XML and add CircularImageView library in your project or you can also grab it through Gradle:

Gradle

You may use the following properties in your XML to change your CircularImageView.

To add shadow in your circular imageview you have to add property add_shadow= “true”

/* circular imageview xml */

  • app.border_width (Dimension) -> default 0dp
  • app.border_color (Color) -> default White
  • app.add_shadow (boolean) -> default false
  • app.shadow_color (Color) -> default Black
  • app.shadow_radius (float) -> default 10
  • app.shadow_radius (float) -> default 10

/* Rounded corner imageview xml */

  • app.rounded_radius (float) -> default 20
  • Now you can load high resolution images without getting outOfmemory exception, all you need to do is call mehtod * loadHighResolutionImage and pass the path of image as arguments

This method can be load image upto 2MB, 5MB, 10MB, i did’nt know the limitation that how much it can load.

How to Make an Imageview With Rounded Corners

This is pretty late in response, but for anyone else that is looking for this, you can do the following code to manually round the corners of your images.

This isn’t my code, but I’ve used it and it’s works wonderfully. I used it as a helper within an ImageHelper class and extended it just a bit to pass in the amount of feathering I need for a given image.

Final code looks like this:

How to make an ImageView with rounded corners?

This is pretty late in response, but for anyone else that is looking for this, you can do the following code to manually round the corners of your images.

This isn’t my code, but I’ve used it and it’s works wonderfully. I used it as a helper within an ImageHelper class and extended it just a bit to pass in the amount of feathering I need for a given image.

Final code looks like this:

Imageview not showing rounded corners

Just use the ShapeableImageView in the Material Components library.

Sample Image

*Note: it requires at least the version 1.2.0-alpha03 .

How to quickly make ImageViews with rounded corners?

The solution is pretty simple actually, but yet hasn’t been suggested that much.
A few months ago I was searching for a simple solution to get a rounded ImageView, and all I could be able to find was complicated solutions.
I’m writing this answer, since this is not known by everybody (and this solution has been implemented in Android at the end of 2020), so that if someone new to Android Studio will have the same question will be able to quickly find a simple solution to make any ImageView rounded.

First thing first, since the solution is implemented in an androidx library, you should make sure that you’re declaring this dependency in your gradle:

After syncing your gradle, you will be able to use a component called "ImageFilterView".

ImageFilterView is sub-class of ImageView, so it inherits everything from a common ImageView, but there are a few things added in order to manipulate the image.
Among these new things, there is the attribute "roundPercent" which allows you to set how much the corners of the image should be rounded.
Remember that this is a percentage value, so it must be a float between 0.0 and 1.0 included.
Settings this attribute to 1.0 will make the image totally circular.

That’s all, nothing else to do, this will be enough to get a rounded ImageView:

(Remember that you have to define the "app" namespace at the beginning of the first layout of your xml file in order to be able to use it:

Rounded corner image view with a custom view

First of all, you are not drawing on the view ‘s canvas, you’ve to override onDraw to draw anything on the view ‘s canvas. And, as you just want to make your image circular from the corners, you don’t need PorterDuff for this. You can just clip a rounded rect from the canvas and it would be suffice for your use case.

You don’t have to manually override each constructor of the AppCompatImageView , You can use the @JvmOverloads annotation to override every constructor of the java class in kotlin .

Use withStyledAttributes extension function of core-ktx to access attributeSet

init block can be used to execute code just after the primary constructor .

Don’t do object allocation inside of onDraw , reuse expensive objects like paint and path as much as possible.

Keeping above points in mind, your class can be changed like this

Now, it can be used like this

ImageView with only bottom or top corners rounded

Here is the another way to do this using Material Design ShapeableImageView

Create one theme for shape and cornerFamily

Now add ShapeableImageView in XML:

I you want to full rounded ShapeableImageView:

Full Rounded Output:

Sample Image

That’s it Happy Coding :).

ImageView rounded corners

I use Universal Image loader library to download and round the corners of image, and it worked for me.

How to make a Circular Image View in Android without Third-Party Library

In this tutorial, we are going to see how to create a circular image view and a circular image view with border-color in Android. Most of the time the android developers use a third-party library for creating a circular profile image, but this tutorial will explain how to create a circular image view without the help of the third-party library and plugins as well.

Most of the time the usage of third-party libraries degrade the speed and affect the data in an android application.

One of the most common tasks in android is to create a Circular ImageView. The default ImageView in android is rectangle so there are situations where we will have to create a circular ImageView.

There are different ways to achieve this but before that let us see the result of what we have to achieve. The image below represents the circular image view in the android application.

Steps:

1. Adding Support Library

You need to add the following support libraries to Gradle (Module.app) for CardView to work on your project.

Picasso and glide libraries are used for loading the image from the browser or server. Here, we use these libraries following.

2. Creating Circular ImageView without border-color

We have to create an empty activity and name it as activity_main.xml and MainActivity.java for our future use. In this stage, XML acts as a major role in creating a circular ImageView. You can define the XML code as follows…

activity_main.xml

You have to put your ImageView inside the CardView because CardView only has a feature of accessing the corner radius attribute. This corner radius attribute helps us to create a rounded ImageView. If you forget to do the below step, your image won't look circular. It will either look like a rectangle or rectangle with a corner radius.

IMPORTANT NOTE: CardView app:cardCornerRadius will double half of your CardView width and height. app:cardCornerRadius always depends on the height and width attribute of the CardView.

3. Creating Circular ImageView with border-color

  • Create drawable.xml for circular shape with border-color
  • Rewrite activity_main.xml for border-color
Create drawable.xml for circular shape with border-color

You have to create the cicular_bordershape.xml under the drawable folder. It will set the border color for the ImageView. You can define the XML code as follows…

circular_bordershape.xml

IMPORTANT NOTE: <stroke> is used to set the border width and as well as the border color.

Rewrite activity_main.xml for border-color

This is how you rewrite the activity_main.xml code for border-color. You can define the XML code as follows…

activity_main.xml

The CardView should be placed inside the RelativeLayout. We use this RelativeLayout to apply the background as drawable.xml for border-color, it gives your ImageView with border-color.

IMPORTANT NOTE:

RelativeLayout height and width calculation formula:-

(dp- Density independent pixels)

4. Load the image using Glide and Picasso tool

As mentioned above, Glide and Picasso libraries are used for loading the images from the server or browser. That's why we use these libraries for image loading. Custom view also loads the image from the server.

MainActivity.java

This brings us to the end of the blog post. I hope you have learned about creating circular imageview with a border for your android application. Now, you can run this on your android device and see the output for yourself.

Last updated: July 27th, 2023 at 9:47:46 AM GMT+0

Hellonext is a user feedback tool and this article was written by many people at Hellonext. Hellonext helps prioritize product roadmap based on user-input.

Как сделать ImageView с закругленными углами?

В Android, ImageView по умолчанию является прямоугольником. Как я могу сделать это округленным прямоугольником (клип со всех четырех углов моего растрового изображения, чтобы быть закругленными прямоугольниками) в ImageView?

41 ответ

Это довольно поздно в ответ, но для тех, кто ищет это, вы можете сделать следующий код для ручного округления углов ваших изображений.

Это не мой код, но я использовал его, и он отлично работает. Я использовал его как помощник в классе ImageHelper и расширил его лишь немного, чтобы передать количество оперения, которое мне нужно для данного изображения.

Конечный код выглядит следующим образом:

Надеюсь, это поможет кому-то!

В то время как вышеприведенный ответ работает, Ромен Гай (основной разработчик Android) показывает лучший метод в своем блоге, который использует меньше памяти, используя шейдер, не создающий копию растрового изображения. Общий смысл функциональности:

Преимущества этого по сравнению с другими методами заключаются в том, что он:

  • не создает отдельную копию растрового изображения, которая использует большое количество памяти с большими изображениями [в отличие от большинства других ответов здесь]
  • поддерживает сглаживание [против метода clipPath]
  • поддерживает alpha [vs xfermode + porterduff method]
  • поддерживает аппаратное ускорение [vs clipPath method]
  • только рисует один раз на холст [vs xfermode и методы клипа]

Я создал RoundedImageView на основе этого кода, который переносит эту логику в ImageView и добавляет правильную поддержку ScaleType и необязательная закругленная граница.

В v21 библиотеки поддержки теперь есть решение: RoundedBitmapDrawable.

Это в основном так же, как обычный Drawable, за исключением того, что вы даете ему угловой радиус для отсечения с помощью:

Итак, начиная с Bitmap src и цели ImageView , он будет выглядеть примерно так:

Еще один простой способ — использовать CardView с радиусом угла и ImageView внутри:

Изображение 3111

Обрезание до округлых фигур было добавлено в класс View в API 21.

Просто выполните следующее:

  • Создайте закругленную фигуру, что-то вроде этого:
  • Задайте для рисования как ваш фон ImageView: android:background=»@drawable/round_outline»
  • В соответствии с этой документацией, все, что вам нужно сделать, это добавить android:clipToOutline=»true»

К сожалению, ошибка и что атрибут XML не распознается. К счастью, мы все же можем настроить обрезку в Java:

  • В вашей деятельности или фрагменте: ImageView.setClipToOutline(true)

Вот как это будет выглядеть:

Изображение 3112

Примечание:

Этот метод работает для любой выталкиваемой формы (не только округленной). Он будет обрезать ImageView в любой форме контура, который вы определили в своем Drawable xml.

Особое примечание о ImageViews

setClipToOutline() работает только тогда, когда фон «Вид» установлен в форму, пригодную для рисования. Если эта фоновая форма существует, View рассматривает контур фигуры как границы для целей отсечения и затенения.

Это означает, что если вы хотите использовать setClipToOutline() для округления углов на ImageView, ваше изображение должно быть установлено с помощью android:src вместо android:background (так как фон должен быть установлен на закругленную фигуру). Если вы ДОЛЖНЫ использовать фон для установки изображения вместо src, вы можете использовать это обходное решение:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *