Ecrire un texte sur une image (BitmapSource)
Par Eric. WPF BitmapSource DrawingVisual RenderTargetBitmap | Lien permanent.
J'ai eu besoin d'écrire sur une image BitmapSource. Le principe est assez simple mais j'ai eu du mal à le trouver, finalement sur le forum de MSDN: il consiste à créer un DrawingVisual, rendre l'image sur ce dernier, rendre le texte, puis rendre le tout dans un RenderTargetImage.
using System.Windows.Media;
using System.Windows.Media.Imaging;
/// <summary>
/// <para>Ecrit un texte sur une <see cref="BitmapSource"/> et retourne la nouvelle image rendue.</para>
/// </summary>
/// <param name="image">Image source</param>
/// <param name="text">Texte à rendre</param>
/// <param name="location">Point d'insertion du texte</param>
/// <param name="size">Taille de police</param>
/// <param name="color">Couleur du texte</param>
public static BitmapSource Write(BitmapSource image, string text, Point location, int size, SolidColorBrush color)
{
// Cible de rendu:
RenderTargetBitmap renderer = new RenderTargetBitmap(
image.PixelWidth, // Largeur
image.PixelHeight, // Hauteur
image.DpiX, // Résolution X
image.DpiY, // Y
PixelFormats.Pbgra32); // Codage pixels
#region Traitement de l'image dans un DrawingVisual
DrawingVisual drawingVisual = new DrawingVisual();
// Retrieve the DrawingContext in order to create new drawing content.
DrawingContext drawingContext = drawingVisual.RenderOpen();
// draw the image and text in the DrawingContext.
Rect rect = new Rect(new Size(image.Width, image.Height));
drawingContext.DrawImage(image, rect);
FormattedText formatted = new FormattedText(
text,
System.Threading.Thread.CurrentThread.CurrentUICulture,
FlowDirection.LeftToRight,
new Typeface("Verdana"),
size,
color);
drawingContext.DrawText(formatted, location);
// Persist the drawing content.
drawingContext.Close();
#endregion
renderer.Render(drawingVisual);
return renderer;
}
Il s'agit d'une reprise de la source trouvée sur: http://social.msdn.microsoft.com/Forums/en/wpf/thread/e1b4568b-c250-487d-bd1e-a903775a3d90