如何制作带圆角的ImageView? [英] How to make an ImageView with rounded corners?

查看:200
本文介绍了如何制作带圆角的ImageView?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Android中,默认情况下ImageView是一个矩形。如何在ImageView中将其设置为圆角矩形(将我的Bitmap的所有4个角切掉为圆角矩形)?

In Android, an ImageView is a rectangle by default. How can I make it a rounded rectangle (clip off all 4 corners of my Bitmap to be rounded rectangles) in the ImageView?

推荐答案

虽然上述答案有效,但Romain Guy(核心Android开发人员)显示一个更好的方法在他的博客中使用更少的内存使用着色器不创建位图的副本。该功能的一般要点如下:

While the above answer works, Romain Guy (a core Android developer) shows a better method in his blog which uses less memory by using a shader not creating a copy of the bitmap. The general gist of the functionality is here:

BitmapShader shader;
shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);

Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setShader(shader);

RectF rect = new RectF(0.0f, 0.0f, width, height);

// rect contains the bounds of the shape
// radius is the radius in pixels of the rounded corners
// paint contains the shader that will texture the shape
canvas.drawRoundRect(rect, radius, radius, paint);

与其他方法相比,优势在于:

The advantages of this over other methods is that it:


  • 不创建位图的单独副本,它使用大量内存和大图像[与此处大多数其他答案相比]

  • 支持 antialisasing [vs clipPath方法]

  • 支持 alpha [vs xfermode + porterduff方法]

  • 支持硬件加速 [vs clipPath方法]

  • 绘制一次到画布 [ vs xfermode和clippath方法]

  • does not create a separate copy of the bitmap, which uses a lot of memory with large images [vs most of the other answers here]
  • supports antialisasing [vs clipPath method]
  • supports alpha [vs xfermode+porterduff method]
  • supports hardware acceleration [vs clipPath method]
  • only draws once to the canvas [vs xfermode and clippath methods]

我创建了一个 RoundedImageView 基于此代码将此逻辑包装到ImageView中并添加适当的 ScaleType 支持和可选的圆形边框。

I've created a RoundedImageView based off this code that wraps this logic into an ImageView and adds proper ScaleType support and an optional rounded border.

这篇关于如何制作带圆角的ImageView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆