首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在android画布中如何绘制透明黑白背景的矩形

在android画布中如何绘制透明黑白背景的矩形
EN

Stack Overflow用户
提问于 2022-07-22 18:28:59
回答 1查看 175关注 0票数 0

如何实现具有黑白透明背景的矩形。我想要像https://i.stack.imgur.com/krsPI.jpg这样的东西

请帮助我在Android上实现同样的结果。这是我的函数,它使用画布创建矩形。

代码语言:javascript
运行
复制
private void drawRectangle() {
    Bitmap bitmap = Bitmap.createBitmap(500, 500, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    Paint paint = new Paint();
    paint.setStyle(Paint.Style.FILL);
    paint.setColor(Color.parseColor("#D20E0F02"));
    canvas.drawRect(400, 180, 80, 350, paint);
}
EN

回答 1

Stack Overflow用户

发布于 2022-07-22 19:49:13

Android在API 29中引入了BlendModes,这是将零饱和颜色应用于Paint并用于去饱和图像的一种非常简单的方法:

代码语言:javascript
运行
复制
Paint paint = new Paint();
paint.setBlendMode(BlendMode.SATURATION);
// just for illustration - it's black by default anyway (zero saturation)
paint.setColor(Color.GRAY);

canvas.drawRect(rect, paint);

不幸的是,据我所知,如果您想要与API 29之前的任何东西兼容,那么您就不走运了--有许多BlendModeCompat类,但是它们回到了PorterDuff混合的旧API上,这不能达到饱和,所以它直接起不了作用,即使使用BlendModeCompat.SATURATION,也会收到兼容性警告。

因此,您可以在您的Paint上设置一个Paint,使用饱和设置为零的ColorMatrix。这不是一个混合模式,它只会影响您正在绘制的东西的外观,因此您基本上必须使用此油漆重新绘制位图的一部分:

代码语言:javascript
运行
复制
ColorMatrix matrix = new ColorMatrix();
matrix.setSaturation(0f);
paint.setColorFilter(new ColorMatrixColorFilter(matrix));

// I don't know how you're getting your bitmaps, but here's an example of pulling one
// from an ImageView, drawing on it, and setting it on the ImageView again
Bitmap bitmap = imageView.drawable.toBitmap();
Canvas canvas = new Canvas(bitmap);
// using the same rect so we're copying and pasting the exact same region
canvas.drawBitmap(bitmap, rect, rect, paint);
imageView.setImageBitmap(bitmap);

我不知道是否有更好的选择(当然还有更复杂的选择!)但希望这能给你一些想法,如何使它适应你正在做的事情。另外,您还需要另一个Paint来在rect周围绘制红色边框!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73084654

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档