gpt4 book ai didi

android - 如何在圆形中显示方形图像?

转载 作者:行者123 更新时间:2023-11-29 14:14:54 27 4
gpt4 key购买 nike

我正在尝试从我的应用程序的 iPhone 版本中模仿一些东西。我有一个方形图像,我想将它显示在一个带有白色边框的圆圈中。像这样

enter image description here

我有办法做到这一点吗?

最佳答案

您可以使用自定义 Drawable 类实现此效果或非常接近它的效果,该类包含一个带有将图像渲染为纹理的 BitmapShader 的 Paint 对象。这是我正在使用的代码(略微改编自 Romain's Guy post ,它使用相同的技术来绘制带圆角的图像)。

class CircularDrawable extends Drawable
{
private float mCircleRadius;
private final RectF mBackgroundRect = new RectF();
private final Paint mBackgroundPaint;
private final BitmapShader mBitmapShader;
private final Paint mPaint;
private final int mMargin;

CircularDrawable(Bitmap bitmap, int margin, int backgroundColor)
{
mBitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);

mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setShader(mBitmapShader);

mMargin = margin;
mBackgroundPaint = new Paint();
mBackgroundPaint.setColor(backgroundColor);
}

@Override
protected void onBoundsChange(Rect bounds)
{
super.onBoundsChange(bounds);
mBackgroundRect.set(bounds);
mCircleRadius = Math.min(bounds.width() / 2 - mMargin, bounds.height() / 2 - mMargin);
}

@Override
public void draw(Canvas canvas)
{
canvas.drawRect(mBackgroundRect, mBackgroundPaint);
canvas.drawCircle(mBackgroundRect.width() / 2, mBackgroundRect.height() / 2, mCircleRadius, mPaint);
}

@Override
public int getOpacity()
{
return PixelFormat.TRANSLUCENT;
}

@Override
public void setAlpha(int alpha)
{
mPaint.setAlpha(alpha);
mBackgroundPaint.setAlpha(alpha);
}

@Override
public void setColorFilter(ColorFilter cf)
{
mPaint.setColorFilter(cf);
mBackgroundPaint.setColorFilter(cf);
}
}

有了你想要绘制的位图,只需用它构建一个 CircularDrawable

new CircularDrawable(bitmap, margin, Color.WHITE);

关于android - 如何在圆形中显示方形图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23576474/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com