visual c# - onPaint and transparency - c#

I am making a simple form with two semi-transparent texts
and i put it in a paint event.
only, when I wider the form, the texts turn darker and grainy.
actualy I want the darker color but not the grainy effect.
here is my code snippet:
private void sbfToolBox_Paint(object sender, PaintEventArgs e)
{
System.Drawing.Graphics formGraphics = this.CreateGraphics();
formGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
string drawString = "tekst";
System.Drawing.Font drawFont = new System.Drawing.Font("Arial", 50);
Color color_red = Color.FromArgb(30, 100, 0, 0);
Color color_cyan = Color.FromArgb(30, 0, 100, 100);
System.Drawing.SolidBrush brush_red = new System.Drawing.SolidBrush(color_red);
System.Drawing.SolidBrush brush_cyan = new System.Drawing.SolidBrush(color_cyan);
float x = 0.0F;
float x2 = 20.0F;
float y = 50.0F;
formGraphics.DrawString(drawString, drawFont, brush_red, x, y);
formGraphics.DrawString(drawString, drawFont, brush_cyan, x2, y);
drawFont.Dispose();
brush_red.Dispose();
brush_cyan.Dispose();
formGraphics.Dispose();
}
thanks in advance

Use the Graphics object from PaintEventArgs.
Change
System.Drawing.Graphics formGraphics = this.CreateGraphics();
To
System.Drawing.Graphics formGraphics = e.Graphics;
And remove
formGraphics.Dispose();

Related

How to draw text with transparency value with C#?

I create a from with transparent background color and I want to draw "hello" string on the form window with a proper transparency setting:
private void Form1_Paint(object sender, PaintEventArgs e)
{
Bitmap bmp = new Bitmap(150, 50);
Graphics g = Graphics.FromImage(bmp);
g.Clear(Color.Transparent);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.CompositingQuality = CompositingQuality.GammaCorrected;
g.CompositingMode = CompositingMode.SourceOver;
g.TextRenderingHint = TextRenderingHint.SingleBitPerPixel;
g.TextContrast = 10;
Font font = new Font("", 20, FontStyle.Bold);
Color color = ColorTranslator.FromHtml("#D3D3D3");
int opacity = 180;
SolidBrush brush = new SolidBrush(Color.FromArgb(opacity, color));
g.DrawString("hello", font, brush, 10, 10);
g.Save();
g.Dispose();
bmp.MakeTransparent(Color.Transparent);
e.Graphics.DrawImage(bmp, 0, 0);
bmp.Dispose();
}
When I set opacity to 1 or 2, the image text disappears, when set to 3, display dark black color, when set to 254, a little transparent. Anything wrong in my code?
I update code to:
private void Form1_Paint(object sender, PaintEventArgs e)
{
Bitmap bmp = new Bitmap(200, 200);
Graphics g = Graphics.FromImage(bmp);
g.Clear(Color.Black);
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.CompositingQuality = CompositingQuality.GammaCorrected;
g.CompositingMode = CompositingMode.SourceOver;
g.TextRenderingHint = TextRenderingHint.SingleBitPerPixel;
g.TextContrast = 3;
Font font = new Font("", 20, FontStyle.Bold);
Color color = ColorTranslator.FromHtml("#191970");
int opacity = 20;
SolidBrush brush = new SolidBrush(Color.FromArgb(opacity, color));
g.DrawString("hello", font, brush, 20, 20);
bmp.MakeTransparent(Color.Black);
g.Save();
g.Dispose();
e.Graphics.DrawImage(bmp, 0, 0);
bmp.Dispose();
}
Output on screen:

Write a word from a string in a different color using g.DrawString()

I use the function below to draw a string on an image. It words great for the most part when I draw a string using one color.
However I want to have a word be in a different color. For example I want to draw "This is a TEST", I want TEST to be red.
What accomplish this using this method?
System.Drawing.Image newImg = new System.Drawing.Bitmap(500, 500);
pictureBox1.Image = TextOverlay(newImg, "This is a TEST", this.Font, Color.Black, ContentAlignment.MiddleCenter, 0.6F);
I'm referring to this line of code and not the OverlayColor parameter:
g.DrawString(OverlayText, f, b, rect, strFormat);
Here is the complete function:
public static Bitmap TextOverlay(Image img, string OverlayText, Font OverlayFont, Color OverlayColor, System.Drawing.ContentAlignment Position, float PercentFill)
{
// create bitmap and graphics used for drawing
// "clone" image but use 24RGB format
Bitmap bmp = new Bitmap(img.Width, img.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
Graphics g = Graphics.FromImage(bmp);
g.DrawImage(img, 0, 0);
int alpha = 255;
// Create the brush based on the color and alpha
SolidBrush b = new SolidBrush(Color.FromArgb(alpha, OverlayColor));
// Measure the text to render (unscaled, unwrapped)
StringFormat strFormat = StringFormat.GenericTypographic;
SizeF s = g.MeasureString(OverlayText, OverlayFont, 100000, strFormat);
// Enlarge font to specified fill (estimated by AREA)
float zoom = (float)(Math.Sqrt(((double)(img.Width * img.Height) * PercentFill) / (double)(s.Width * s.Height)));
FontStyle sty = OverlayFont.Style;
Font f = new Font(OverlayFont.FontFamily, ((float)OverlayFont.Size) * zoom, sty);
int charFit;
int linesFit;
float SQRTFill = (float)(Math.Sqrt(PercentFill));
strFormat.FormatFlags = StringFormatFlags.NoClip; //|| StringFormatFlags.LineLimit || StringFormatFlags.MeasureTrailingSpaces;
strFormat.Trimming = StringTrimming.Word;
SizeF layout = new SizeF(((float)img.Width) * SQRTFill, ((float)img.Height) * 1.5F); // fit to width, allow height to go over
s = g.MeasureString(OverlayText, f, layout, strFormat, out charFit, out linesFit);
// Determine draw area based on placement
RectangleF rect = new RectangleF((bmp.Width - s.Width) / 2F,
(bmp.Height - s.Height) / 2F,
layout.Width,
((float)img.Height) * SQRTFill);
// Add rendering hint (thx to Thomas)
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
// finally, draw centered text!
g.DrawString(OverlayText, f, b, rect, strFormat);
// clean-up
g.Dispose();
b.Dispose();
f.Dispose();
return bmp;
}

Is it possible to stretch font in WinForms

Is to possible to stretch Font in WinForms? What I am trying to accomplish is to stretch font to maximum available RichTextBox width. It should be something like viewbox in WPF.
My goal is to stretch font NOT TO resize it. All fonts I am using are mono spaced fonts.
yes it's possible to do this
private void button1_Click(object sender, EventArgs e)
{
Graphics gr = richTextBox1.CreateGraphics();
Brush brush = new SolidBrush(Color.Red);
float x = 0.0F;
float y = 0.0F;
float width = 200.0F;
float height = 50.0F;
Font drawFont = new Font("Arial", 18);
RectangleF drawRect = new RectangleF(x, y, width, height);
//here you can shrink as you want
gr.ScaleTransform(3, 1);
gr.DrawString("your text", drawFont, brush, drawRect);
}
Hope this help

Drawing to a new "layer" in C#

Building a little paint program and am trying to incorporate the concept of layers.
I'm using a PictureBox control to display the image, and getting the Graphics object from the image being displayed by the PictureBox and drawing to that.
My problem is I'm trying to figure out how to draw to a new Graphics object that is overlayed on top of the picture box, and be able to get the newly drawn image without the original image absorbed into the graphic.
If I do something like:
Graphics gr = Graphics.FromImage(myPictureBox.image);
gr.DrawRectangle(blah blah)
...I am editing the original image in the picture box. I want a way to only capture the new stuff being drawn as a separate image, but still have it displayed as an overlay over top of what was already there.
Anyone able to point me in the right direction? Thanks!
I would reckon to use the transparent control and do some modification so it can be used as image layers:
http://www.codeproject.com/Articles/26878/Making-Transparent-Controls-No-Flickering
Probably something like this (make any modification as necessary).
class LayerControl : UserControl
{
private Image image;
private Graphics graphics;
public LayerControl(int width, int height)
{
this.Width = width;
this.Height = height;
image = new Bitmap(width, height);
graphics = Graphics.FromImage(image);
// Set style for control
SetStyle(ControlStyles.OptimizedDoubleBuffer |
ControlStyles.AllPaintingInWmPaint |
ControlStyles.UserPaint, true);
}
// this function will draw your image
protected override void OnPaint(PaintEventArgs e)
{
var bitMap = new Bitmap(image);
// by default the background color for bitmap is white
// you can modify this to follow your image background
// or create a new Property so it can dynamically assigned
bitMap.MakeTransparent(Color.White);
image = bitMap;
Graphics g = e.Graphics;
g.SmoothingMode = SmoothingMode.AntiAlias;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.CompositingQuality = CompositingQuality.GammaCorrected;
float[][] mtxItens = {
new float[] {1,0,0,0,0},
new float[] {0,1,0,0,0},
new float[] {0,0,1,0,0},
new float[] {0,0,0,1,0},
new float[] {0,0,0,0,1}};
ColorMatrix colorMatrix = new ColorMatrix(mtxItens);
ImageAttributes imgAtb = new ImageAttributes();
imgAtb.SetColorMatrix(
colorMatrix,
ColorMatrixFlag.Default,
ColorAdjustType.Bitmap);
g.DrawImage(image,
ClientRectangle,
0.0f,
0.0f,
image.Width,
image.Height,
GraphicsUnit.Pixel,
imgAtb);
}
// this function will grab the background image to the control it self
protected override void OnPaintBackground(PaintEventArgs e)
{
base.OnPaintBackground(e);
Graphics g = e.Graphics;
if (Parent != null)
{
BackColor = Color.Transparent;
int index = Parent.Controls.GetChildIndex(this);
for (int i = Parent.Controls.Count - 1; i > index; i--)
{
Control c = Parent.Controls[i];
if (c.Bounds.IntersectsWith(Bounds) && c.Visible)
{
Bitmap bmp = new Bitmap(c.Width, c.Height, g);
c.DrawToBitmap(bmp, c.ClientRectangle);
g.TranslateTransform(c.Left - Left, c.Top - Top);
g.DrawImageUnscaled(bmp, Point.Empty);
g.TranslateTransform(Left - c.Left, Top - c.Top);
bmp.Dispose();
}
}
}
else
{
g.Clear(Parent.BackColor);
g.FillRectangle(new SolidBrush(Color.FromArgb(255, Color.Transparent)), this.ClientRectangle);
}
}
// simple drawing circle function
public void DrawCircles()
{
using (Brush b = new SolidBrush(Color.Red))
{
using (Pen p = new Pen(Color.Green, 3))
{
this.graphics.DrawEllipse(p, 25, 25, 20, 20);
}
}
}
// simple drawing rectable function
public void DrawRectangle()
{
using (Brush b = new SolidBrush(Color.Red))
{
using (Pen p = new Pen(Color.Red, 3))
{
this.graphics.DrawRectangle(p, 50, 50, 40, 40);
}
}
}
// Layer control image property
public Image Image
{
get
{
return image;
}
set
{
image = value;
// this will make the control to be redrawn
this.Invalidate();
}
}
}
Example how to use it:
LayerControl lc = new LayerControl(100, 100);
lc.Location = new Point(0, 0);
lc.DrawRectangle();
LayerControl lc2 = new LayerControl(100, 100);
lc2.Location = new Point(0, 0);
lc2.DrawCircles();
LayerControl lc3 = new LayerControl(100, 100);
lc3.Location = new Point(0, 0);
lc3.Image = new Bitmap(#"<Image Path>");
// adding control
this.Controls.Add(dc);
this.Controls.Add(dc2);
this.Controls.Add(dc3);
With this method you can have multiple layers that can put overlapping each other (due to the transparency feature it has).
If you want to add it in top of your PictureBox make sure to re-order the control. The Layer Control should be added before your PictureBox control.
// adding control
this.Controls.Clear();
this.Controls.Add(dc);
this.Controls.Add(dc2);
this.Controls.Add(dc3);
this.Controls.Add(PictureBox1);
Hopefully it help.
example code which working fine - take dummy image and layered the original image with custom text
public void LayerImage(System.Drawing.Image Current, int LayerOpacity)
{
Bitmap bitmap = new Bitmap(Current);
int h = bitmap.Height;
int w = bitmap.Width;
Bitmap backg = new Bitmap(w, h + 20);
Graphics g = null;
try
{
g = Graphics.FromImage(backg);
g.Clear(Color.White);
Font font = new Font("Arial", 12, FontStyle.Bold, GraphicsUnit.Pixel);
RectangleF rectf = new RectangleF(70, 90, 90, 50);
Color color = Color.FromArgb(255, 128, 128, 128);
Point atpoint = new Point(backg.Width / 2, backg.Height - 10);
SolidBrush brush = new SolidBrush(color);
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
g.DrawString("BRAND AMBASSADOR", font, brush, atpoint, sf);
g.Dispose();
MemoryStream m = new MemoryStream();
backg.Save(m, System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch { }
Color pixel = new Color();
for (int x = 0; x < bitmap.Width; x++)
{
for (int y = 0; y < bitmap.Height; y++)
{
pixel = bitmap.GetPixel(x, y);
backg.SetPixel(x, y, Color.FromArgb(LayerOpacity, pixel));
}
}
MemoryStream m1 = new MemoryStream();
backg.Save(m1, System.Drawing.Imaging.ImageFormat.Jpeg);
m1.WriteTo(Response.OutputStream);
m1.Dispose();
base.Dispose();
}
Got it working, perhaps I wasn't clear enough in my original question.
Essentially what I ended up doing was storing each layer as a separate Image object, then just hooking into the OnPaint method of my control and manually drawing the graphics in order, instead of just drawing to PictureBox.Image. Works like a charm!
The graphics capabilities of .NET drawing libraries are simple. Their main purpose is direct drawing of GUI. If you want to have layering, alpha transparency or advanced filters, then you should either use 3rd party library or roll your own drawing code.

.NET Graphics - creating an ellipse with transparent background

The following code will draw an ellipse on an image and fill that ellipse with the Tomato colour
string imageWithTransEllipsePathToSaveTo = "~/Images/imageTest.png";
Graphics g = Graphics.FromImage(sourceImage);
g.FillEllipse(Brushes.Tomato, 50, 50, 200, 200);
sourceImage.Save(Server.MapPath(imageWithTransEllipsePathToSaveTo), ImageFormat.Png);
If I change the brush to Transparent it obviously will not show because the ellipse will be transparent and the image underneath will show.
How do I set the 'background' of the ellipse to be transparent so that the image contains a transparent spot?
EDIT:
Sorry for the confusion but like this...
This is my second answer and works with an Image instead of a color brush. Unfortunately there is no RadialImageBrush (known to me). I've included code to save the image to the disk, and included usings to ensure you import the correct components. This does use WPF but it should work as part of a library or console app.
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Shapes;
namespace WpfApplication30
{
class ImageEditor
{
public static void processImage(string loc)
{
ImageSource ic = new BitmapImage(new Uri(loc, UriKind.Relative));
ImageBrush brush = new ImageBrush(ic);
Path p = new Path();
p.Fill = brush;
CombinedGeometry cb = new CombinedGeometry();
cb.GeometryCombineMode = GeometryCombineMode.Exclude;
EllipseGeometry ellipse = new EllipseGeometry(new Point(50, 50), 5, 5);
RectangleGeometry rect = new RectangleGeometry(new Rect(new Size(100, 100)));
cb.Geometry1 = rect;
cb.Geometry2 = ellipse;
p.Data = cb;
Canvas inkCanvas1 = new Canvas();
inkCanvas1.Children.Add(p);
inkCanvas1.Height = 96;
inkCanvas1.Width = 96;
inkCanvas1.Measure(new Size(96, 96));
inkCanvas1.Arrange(new Rect(new Size(96, 96)));
RenderTargetBitmap targetBitmap =
new RenderTargetBitmap((int)inkCanvas1.ActualWidth,
(int)inkCanvas1.ActualHeight,
96d, 96d,
PixelFormats.Default);
targetBitmap.Render(inkCanvas1);
using (System.IO.FileStream outStream = new System.IO.FileStream( loc.Replace(".png","Copy.png"), System.IO.FileMode.Create))
{
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(targetBitmap));
encoder.Save(outStream);
}
}
}
}
Here is the result:
You need to create a brush using a semi-transparent color.
You do that with Color.FromArgb(alpha, r, g, b), where alpha sets the opacity.
Example copied from MSDN:
public void FromArgb1(PaintEventArgs e)
{
Graphics g = e.Graphics;
// Transparent red, green, and blue brushes.
SolidBrush trnsRedBrush = new SolidBrush(Color.FromArgb(120, 255, 0, 0));
SolidBrush trnsGreenBrush = new SolidBrush(Color.FromArgb(120, 0, 255, 0));
SolidBrush trnsBlueBrush = new SolidBrush(Color.FromArgb(120, 0, 0, 255));
// Base and height of the triangle that is used to position the
// circles. Each vertex of the triangle is at the center of one of the
// 3 circles. The base is equal to the diameter of the circles.
float triBase = 100;
float triHeight = (float)Math.Sqrt(3*(triBase*triBase)/4);
// Coordinates of first circle's bounding rectangle.
float x1 = 40;
float y1 = 40;
// Fill 3 over-lapping circles. Each circle is a different color.
g.FillEllipse(trnsRedBrush, x1, y1, 2*triHeight, 2*triHeight);
g.FillEllipse(trnsGreenBrush, x1 + triBase/2, y1 + triHeight,
2*triHeight, 2*triHeight);
g.FillEllipse(trnsBlueBrush, x1 + triBase, y1, 2*triHeight, 2*triHeight);
}
You need to use a RadialGradientBrush:
RadialGradientBrush b = new RadialGradientBrush();
b.GradientOrigin = new Point(0.5, 0.5);
b.Center = new Point(0.5, 0.5);
b.RadiusX = 0.5;
b.RadiusY = 0.5;
b.GradientStops.Add(new GradientStop(Colors.Transparent,0));
b.GradientStops.Add(new GradientStop(Colors.Transparent,0.25));
b.GradientStops.Add(new GradientStop(Colors.Tomato, 0.25));
g.FillEllipse(b, 50, 50, 200, 200);

Categories