在Android中,ImageView默认是一个矩形。如何使它成为一个圆角矩形(剪辑我的位图的所有4个角为圆角矩形)在ImageView?
请注意,从2021年起,只需使用ShapeableImageView
在Android中,ImageView默认是一个矩形。如何使它成为一个圆角矩形(剪辑我的位图的所有4个角为圆角矩形)在ImageView?
请注意,从2021年起,只需使用ShapeableImageView
当前回答
你可以在你的布局中只使用ImageView,使用滑动,你可以使用这个方法应用圆角。
首先在你的gradle里写上,
compile 'com.github.bumptech.glide:glide:3.7.0'
对于有圆角的图像,
public void loadImageWithCorners(String url, ImageView view) {
Glide.with(context)
.load(url)
.asBitmap()
.centerCrop()
.placeholder(R.color.gray)
.error(R.color.gray)
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.into(new BitmapImageViewTarget(view) {
@Override
protected void setResource(Bitmap resource) {
RoundedBitmapDrawable circularBitmapDrawable =
RoundedBitmapDrawableFactory.create(context.getResources(), resource);
circularBitmapDrawable.setCornerRadius(32.0f); // radius for corners
view.setImageDrawable(circularBitmapDrawable);
}
});
}
调用方法:
loadImageWithCorners("your url","your imageview");
其他回答
虽然前两个答案是可行的,但我希望再多描述一点。 比如说,ImageView所在的地方有一个活动或片段。您希望绘制图像并按比例缩放。然后你应该在onCreate或onCreateView中写入如下代码:
LinearLayout rootLayout = (LinearLayout) findViewById(R.id.rootLayout);
ImageView image = (ImageView) findViewById(R.id.image);
// Wait till an activity is visible and image can be measured.
rootLayout.post(new Runnable() {
@Override
public void run() {
// Setting ImageView height with aspect ratio.
Drawable drawable = ContextCompat.getDrawable(getActivity(), R.drawable.your_image);
int height = getImageViewHeight(drawable, image);
// Rounding image corners.
float radius = getResources().getDimension(R.dimen.your_radius_in_dp);
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
Bitmap result = getRoundedBitmap(bitmap, image.getWidth(), height, radius);
image.setImageBitmap(result);
}
});
其中设置新的图像高度为:
public static int getImageViewHeight(Drawable drawable, ImageView imageView) {
imageView.setImageDrawable(drawable);
int width = drawable.getIntrinsicWidth();
int height = 0;
if (width > 0) {
height = (drawable.getIntrinsicHeight() * imageView.getWidth()) / width;
imageView.getLayoutParams().height = height;
imageView.requestLayout();
}
return height;
}
然后,您应该编写一个方法来缩放图像并使其圆角。这里的width和height是位图的新维度(更小或更大)。在下面的例子中,我只圆角上的两个角。
private Bitmap getRoundedBitmap(Bitmap bitmap, int width, int height, float radius) {
// Create scaled bitmap.
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, width, height, false);
BitmapShader shader = new BitmapShader(scaledBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setShader(shader);
Bitmap result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(result);
// First make all corners round.
canvas.drawRoundRect(new RectF(0, 0, width, height), radius, radius, paint);
// Then draw bottom rectangle.
canvas.drawRect(0, height - radius, radius, height, paint);
canvas.drawRect(width - radius, height - radius, width, height, paint);
return result;
}
让你的ImageView像这样:
<com.example..CircularImageView
android:id="@+id/profile_image_round_corner"
android:layout_width="80dp"
android:layout_height="80dp"
android:scaleType="fitCenter"
android:padding="2dp"
android:background="@null"
android:adjustViewBounds="true"
android:layout_centerInParent="true"
android:src="@drawable/dummy"
/>
并创建一个类:
package com.example;
import java.util.Formatter.BigDecimalLayoutForm;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
public class CircularImageView extends ImageView {
public CircularImageView(Context context) {
super(context);
}
public CircularImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CircularImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
if (drawable == null) {
return;
}
if (getWidth() == 0 || getHeight() == 0) {
return;
}
Bitmap b = ((BitmapDrawable) drawable).getBitmap();
Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);
int w = getWidth(), h = getHeight();
Bitmap roundBitmap = getRoundBitmap(bitmap, w);
canvas.drawBitmap(roundBitmap, 0, 0, null);
}
public static Bitmap getRoundBitmap(Bitmap bmp, int radius) {
Bitmap sBmp;
if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
float factor = smallest / radius;
sBmp = Bitmap.createScaledBitmap(bmp, (int)(bmp.getWidth() / factor), (int)(bmp.getHeight() / factor), false);
} else {
sBmp = bmp;
}
Bitmap output = Bitmap.createBitmap(radius, radius, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xffa19774;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, radius, radius);
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(Color.parseColor("#BAB399"));
canvas.drawCircle(radius / 2 + 0.7f,
radius / 2 + 0.7f, radius / 2 + 0.1f, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(sBmp, rect, rect, paint);
return output;
}
}
如果你不希望边框影响图像,使用这个类。不幸的是,我没有找到任何方法来绘制画布上的透明区域来到onDraw()。这里创建了一个新的位图它是画在一个真实的画布上的。
如果您想要创建一个消失的边界,该视图非常有用。如果你将borderWidth设置为0,边框将会消失,图像仍然保持圆角,就像边界一样。也就是说,它看起来就像边界完全由图像边缘绘制。
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import android.graphics.RectF
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView
class RoundedImageViewWithBorder @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0) : AppCompatImageView(context, attrs, defStyleAttr) {
var borderColor: Int = 0
set(value) {
invalidate()
field = value
}
var borderWidth: Int = 0
set(value) {
invalidate()
field = value
}
var cornerRadius: Float = 0f
set(value) {
invalidate()
field = value
}
private var bitmapForDraw: Bitmap? = null
private var canvasForDraw: Canvas? = null
private val transparentPaint = Paint().apply {
isAntiAlias = true
color = Color.TRANSPARENT
style = Paint.Style.STROKE
xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC)
}
private val borderPaint = Paint().apply {
isAntiAlias = true
style = Paint.Style.STROKE
}
private val transparentAreaRect = RectF()
private val borderRect = RectF()
init {
val typedArray = context.obtainStyledAttributes(attrs, R.styleable.RoundedImageViewWithBorder)
try {
borderWidth = typedArray.getDimensionPixelSize(R.styleable.RoundedImageViewWithBorder_border_width, 0)
borderColor = typedArray.getColor(R.styleable.RoundedImageViewWithBorder_border_color, 0)
cornerRadius = typedArray.getDimensionPixelSize(R.styleable.RoundedImageViewWithBorder_corner_radius, 0).toFloat()
} finally {
typedArray.recycle()
}
}
@SuppressLint("CanvasSize", "DrawAllocation")
override fun onDraw(canvas: Canvas) {
if (canvas.height <=0 || canvas.width <=0) {
return
}
if (canvasForDraw?.height != canvas.height || canvasForDraw?.width != canvas.width) {
val newBitmap = Bitmap.createBitmap(canvas.width, canvas.height, Bitmap.Config.ARGB_8888)
bitmapForDraw = newBitmap
canvasForDraw = Canvas(newBitmap)
}
bitmapForDraw?.eraseColor(Color.TRANSPARENT)
// Draw existing content
super.onDraw(canvasForDraw)
if (borderWidth > 0) {
canvasForDraw?.let { drawWithBorder(it) }
} else {
canvasForDraw?.let { drawWithoutBorder(it) }
}
// Draw everything on real canvas
bitmapForDraw?.let { canvas.drawBitmap(it, 0f, 0f, null) }
}
private fun drawWithBorder(canvas: Canvas) {
// Draw transparent area
transparentPaint.strokeWidth = borderWidth.toFloat() * 4
transparentAreaRect.apply {
left = -borderWidth.toFloat() * 1.5f
top = -borderWidth.toFloat() * 1.5f
right = canvas.width.toFloat() + borderWidth.toFloat() * 1.5f
bottom = canvas.height.toFloat() + borderWidth.toFloat() * 1.5f
}
canvasForDraw?.drawRoundRect(transparentAreaRect, borderWidth.toFloat() * 2 + cornerRadius, borderWidth.toFloat() * 2 + cornerRadius, transparentPaint)
// Draw border
borderPaint.color = borderColor
borderPaint.strokeWidth = borderWidth.toFloat()
borderRect.apply {
left = borderWidth.toFloat() / 2
top = borderWidth.toFloat() / 2
right = canvas.width.toFloat() - borderWidth.toFloat() / 2
bottom = canvas.height.toFloat() - borderWidth.toFloat() / 2
}
canvas.drawRoundRect(borderRect, cornerRadius - borderWidth.toFloat() / 2, cornerRadius - borderWidth.toFloat() / 2, borderPaint)
}
private fun drawWithoutBorder(canvas: Canvas) {
// Draw transparent area
transparentPaint.strokeWidth = cornerRadius * 4
transparentAreaRect.apply {
left = -cornerRadius * 2
top = -cornerRadius * 2
right = canvas.width.toFloat() + cornerRadius * 2
bottom = canvas.height.toFloat() + cornerRadius * 2
}
canvasForDraw?.drawRoundRect(transparentAreaRect, cornerRadius * 3, cornerRadius * 3, transparentPaint)
}
}
值:
<declare-styleable name="RoundedImageViewWithBorder">
<attr name="corner_radius" format="dimension|string" />
<attr name="border_width" format="dimension|reference" />
<attr name="border_color" format="color|reference" />
</declare-styleable>
通过使用下面的代码,您可以改变顶部角半径
val image = findViewById<ImageView>(R.id.image)
val curveRadius = 20F
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
image.outlineProvider = object : ViewOutlineProvider() {
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun getOutline(view: View?, outline: Outline?) {
outline?.setRoundRect(0, 0, view!!.width, (view.height+curveRadius).toInt(), curveRadius)
}
}
image.clipToOutline = true
}
对我来说,下面的解决方案似乎是最优雅的:
ImageView roundedImageView = new ImageView (getContext());
roundedImageView.setClipToOutline(true);
Bitmap bitmap = AppUtil.decodeSampledBitmapFromResource(new File(valueListItemsView.getImagePath()), width, height);
roundedImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
roundedImageView.setImageBitmap(bitmap);
roundedImageView.setBackgroundResource(R.drawable.rounded_corner);
而可绘制的rounded_corner.xml的代码是:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/colorAccent" />
<corners android:radius="24dp" />
</shape>