[cairo] Replicating Microsoft's AlphaBlend function with Cairo

Chris Wilson chris at chris-wilson.co.uk
Fri Aug 24 07:34:29 PDT 2012


On Fri, 24 Aug 2012 10:11:08 -0400, Anthony Walter <sysrpl at gmail.com> wrote:
> How can I stretch draw an area of a gdk pixbuf to a cairo surface with a
> user defined opacity?
> 
> I am trying to write a cross platform interface for working with bitmaps
> and want to add alpha blending to my cairo stretch draw method. What I have
> right now works just fine, but I am unable to think up a way of to mold
> alpha blending into a series of cairo/gdk apis which work somewhat like
> Microsoft's [AlphaBlend][1] function.
> 
> What I have so far is this:
> 
>     procedure TGtkBitmap.Draw(const Source: TRect; Canvas: TCanvas;
>       const Dest: TRect; Alpha: Byte = $FF);
>     var
>       D: PGdkDrawable;
>       C: Pcairo_t;
>       M: cairo_matrix_t;
>     begin
>       if FBuffer = nil then
>         Exit;
>       if (WidthOf(Source) < 1) or (WidthOf(Dest) < 1) then
>         Exit;
>       if (HeightOf(Source) < 1) or (HeightOf(Dest) < 1) then
>         Exit;
>       D := TGtk2DeviceContext(Canvas.Handle).Drawable;
>       C := gdk_cairo_create(D);
>       gdk_cairo_set_source_pixbuf(C, FBuffer, 0, 0);
>       cairo_matrix_init_identity(@M);
>       cairo_matrix_translate(@M, Source.Left, Source.Top);
>       cairo_matrix_scale(@M, WidthOf(Source) / WidthOf(Dest),
>         HeightOf(Source) / HeightOf(Dest));
>       cairo_matrix_translate(@M, -Dest.Left, -Dest.Top);
>       cairo_pattern_set_matrix(cairo_get_source(C), @M);
>       cairo_rectangle(C, Dest.Left, Dest.Top, WidthOf(Dest),
> HeightOf(Dest));
>       // what cairo functions can I combine here to vary
>       // the opacity of the pattern fill using Alpha argument?
>       cairo_fill(C);

Replace the fill with: cairo_clip(C); cairo_paint_with_opacity(C, alpha);

>       cairo_destroy(C);
>     end;

I'd been contemplating explicit alpha support ala globalAlpha from the
canvas spec, but the above should solve your problem.

Have fun with Cairo,
-Chris

-- 
Chris Wilson, Intel Open Source Technology Centre


More information about the cairo mailing list