er2cord/src/widgets/Avatar.vala

74 lines
1.8 KiB
Vala

/** Avatar widget
* (c) Er2 2021
* Zlib License
*/
using Cairo;
namespace Er2Cord {
class Avatar : Gtk.DrawingArea {
public ImageSurface ava;
public int size;
public int round;
public Avatar(ImageSurface ava,
int size = 32,
int? round = null
) {
if(round == null) round = size / 2;
content_width = size;
content_height = size;
halign = valign = CENTER;
this.ava = ava;
this.size = size;
this.round = round;
set_draw_func((th, cr, w, h) => {
cr.set_source_surface(draw(), 0, 0);
cr.paint();
});
}
public Avatar.gen(string name, double[] colors,
int size = 32,
int? round = null
) {
var sf = new ImageSurface(ARGB32, 256, 256);
var cr = new Context(sf);
cr.set_source_rgb(colors[0], colors[1], colors[2]);
cr.rectangle(0, 0, 256, 256);
cr.paint();
cr.set_source_rgb(1, 1, 1);
cr.move_to(75, 170);
cr.set_font_size(128);
cr.show_text(@"$(name[0])");
this(sf, size, round);
}
public ImageSurface draw() {
var x = 0, y = 0, w = size, h = size;
var sf = new ImageSurface(ARGB32, w, h);
var cr = new Context(sf);
double iw = (double)w / ava.get_width();
double ih = (double)h / ava.get_height();
cr.scale(iw, ih);
cr.set_source_surface(ava, 0, 0);
cr.scale(1.0 / iw, 1.0 / ih);
cr.new_sub_path();
cr.arc(x + round, y + round, round, Math.PI, 3 * Math.PI / 2);
cr.arc(x + w - round, y + round, round, 3 * Math.PI / 2, 2 * Math.PI);
cr.arc(x + w - round, y + h - round, round, 0, Math.PI / 2);
cr.arc(x + round, y + h - round, round, Math.PI / 2, Math.PI);
cr.close_path();
cr.clip();
cr.paint();
return sf;
}
}
}