Skip to content

Commit 7a274d3

Browse files
committed
SkSL_PremultipliedAlpha.py, Based on chrome/m131:docs/examples/SkSL_PremultipliedAlpha.cpp
1 parent 0281e99 commit 7a274d3

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

SkSL_PremultipliedAlpha.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
#
4+
# Copyright 2024 Hin-Tak Leung
5+
# Distributed under the terms of the new BSD license.
6+
#
7+
8+
# Based on chrome/m131:docs/examples/SkSL_PremultipliedAlpha.cpp
9+
# - We check effect being non-NULL here, unlike the c++ example.
10+
11+
from skia import RuntimeEffect, Paint, ColorGRAY
12+
13+
sksl = \
14+
"const half3 iColor = half3(0, 0.5, 0.75);" + \
15+
"half4 main(float2 coord) {" + \
16+
" float alpha = 1 - (coord.y / 150);" + \
17+
" if (coord.x < 100) {" + \
18+
" /* Correctly premultiplied version of color */" + \
19+
" return iColor.rgb1 * alpha;" + \
20+
" } else {" + \
21+
" /* Returning an unpremultiplied color (just setting alpha) leads to over-bright colors. */" + \
22+
" return half4(iColor, alpha);" + \
23+
" }" + \
24+
"}"
25+
26+
def draw(canvas):
27+
autoResult = RuntimeEffect.MakeForShader(sksl)
28+
29+
if (autoResult.effect is None):
30+
raise RuntimeError(autoResult.errorText)
31+
32+
myShader = autoResult.effect.makeShader(None)
33+
34+
canvas.drawColor(ColorGRAY)
35+
36+
p = Paint()
37+
p.setShader(myShader)
38+
canvas.drawPaint(p)
39+
40+
if __name__ == '__main__':
41+
from skia import Surface, kPNG
42+
surface = Surface(200, 200)
43+
with surface as canvas:
44+
draw(canvas)
45+
surface.flushAndSubmit()
46+
image = surface.makeImageSnapshot()
47+
image.save('./output.png', kPNG)

0 commit comments

Comments
 (0)