我正在使用火焰包中的精灵来显示图像。我正在尝试为图像添加透明度或不透明度。
这是我的代码:
void render(Canvas c) {
Sprite spriteImg = Sprite('someImg.png');
rect = Rect.fromLTWH(10, 10, 20, 20);
spriteImg.renderRect(c, rect);
}
我似乎无法弄清楚如何添加不透明度。
您必须覆盖渲染时使用的油漆,如下所示:
void render(Canvas c) {
Sprite spriteImg = Sprite('someImg.png');
rect = Rect.fromLTWH(10, 10, 20, 20);
Paint opacityPaint = Paint()..color = Colors.white.withOpacity(0.5);
spriteImg.renderRect(c, rect, overridePaint: opacityPaint);
}
这将使您的精灵具有 50% 的不透明度。
class NewComponent extends PositionComponent{
static final Color _color = Color(0xFFFFFFFF);
static final Paint _paint = Paint()
..color = _color
..style = PaintingStyle.fill;
Sprite? sprite;
Future<void> onLoad() async {
sprite = await Sprite.load('image.png');
}
@override
void render(Canvas canvas) {
super.render(canvas);
final double colorOpacity = opacity.clamp(0, 1.0);
_paint.color = _color.withOpacity(colorOpacity);
sprite?.render(
canvas,
size: size,
overridePaint: _paint,
);
}
}
动态更新透明度时的重要细节 _paint.color = ? 和opacity.clamp(0, 1.0)