Graphics.DrawImage() clips image when using RotateTransform() - c#

I have following code to draw my border2.bmp in 4 direction
private void Form1_Paint(object sender, PaintEventArgs e)
{
Bitmap border = new Bitmap("border2.bmp");
int borderThick = border.Height;
Graphics g = e.Graphics;
Size region = g.VisibleClipBounds.Size.ToSize();
Rectangle desRectW = new Rectangle(0, 0, region.Width - borderThick, borderThick);
// 1. LEFT - RIGHT border
g.TranslateTransform(30, 30);
g.DrawImage(border, desRectW, desRectW, GraphicsUnit.Pixel);
// 2. UP - BUTTOM border
g.ResetTransform();
g.TranslateTransform(50, 50);
g.RotateTransform(90);
g.DrawImage(border, desRectW, desRectW, GraphicsUnit.Pixel);
// 3. RIGHT-LEFT border
g.ResetTransform();
g.TranslateTransform(100, 100);
g.RotateTransform(180);
g.DrawImage(border, desRectW, desRectW, GraphicsUnit.Pixel);
// 4. BOTTOM - UP border
g.ResetTransform();
g.TranslateTransform(150, 150);
g.RotateTransform(270);
g.DrawImage(border, desRectW, desRectW, GraphicsUnit.Pixel);
}
My original image is:
But the result of rotations are not exactly as I expected. 90 degrees is missing the first red line, 270 degrees is missing first black column, and 180 degrees is missing both.
Like image I attached:
PS: you can get border2.bmp at: http://i.imgur.com/pzonx3i.png
Edit:
I tried g.PixelOffsetMode = PixelOffsetMode.HighQuality; as #Peter Duniho comment, but I found it also does't draw correctly.
Example: 4 line is not starting at same position as we expect.
g.TranslateTransform(50, 50);
// LEFT - RIGHT border
g.DrawLine(Pens.Red, 0, 0, 100, 0);
// UP - BOTTOM border
g.RotateTransform(90);
g.DrawLine(new Pen(Color.FromArgb(128, Color.Blue)), 0, 0, 100, 0);
// RIGHT-LEFT border
g.RotateTransform(90);
g.DrawLine(new Pen(Color.FromArgb(128, Color.Green)), 0, 0, 100, 0);
// BOTTOM - UP border
g.RotateTransform(90);
g.DrawLine(new Pen(Color.FromArgb(128, Color.Gray)), 0, 0, 100, 0);

I can't really explain why this happens, except that any graphics API is necessarily going to include optimizations which may lead to imprecise behaviors at times and it seems that you are running into such a situation here.
In your particular example, the problem can be corrected by adding the following statement to the code, before you draw the images:
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
Setting it to Half will also work. It is equivalent to HighQuality (or technically, HighQuality is equivalent to it…but I find HighQuality more descriptive in the code :) ).
This will slow the rendering of the bitmap down somewhat, but probably not in a way that is perceptible to your users.
While the .NET documentation isn't very helpful in terms of describing this setting, the native Win32 docs for the same feature has slightly more detail:
PixelOffsetMode enumeration. From the description, one can infer that with the logical center of the pixel at (0,0), it's possible to lose a pixel on one edge when rotating (and/or gain a pixel on another edge). Switching to Half fixes this.

You need to account some things.
(1) RotateTransforms applies rotation at the current origin (as explained in the Matrix.Rotate documentation
(2) The default MatrixOrder (when not specified by using the overrides with the additional argument) is Prepend. Which means in your case the resulting transformation is rotate, then translate.
For instance, if you put this code inside the paint event:
var g = e.Graphics;
var loc = new Point(128, 128);
var rect = new Rectangle(0, 0, 64, 16);
g.ResetTransform();
g.TranslateTransform(loc.X, loc.Y);
g.FillRectangle(Brushes.Blue, rect);
g.ResetTransform();
g.TranslateTransform(loc.X, loc.Y);
g.RotateTransform(90);
g.FillRectangle(Brushes.Red, rect);
g.ResetTransform();
g.TranslateTransform(loc.X, loc.Y);
g.RotateTransform(180);
g.FillRectangle(Brushes.Green, rect);
g.ResetTransform();
g.TranslateTransform(loc.X, loc.Y);
g.RotateTransform(270);
g.FillRectangle(Brushes.Magenta, rect);
you'll get this
The blue rectangle is not rotated. Now pin virtually the origin (the upper left point) and start rotating clockwise. You'll see that it will exactly match the Red (90), Green (180) and Magenta (270) rectangles.
What all that means is that if you want to form a rectangle, you need to apply additional offset (translation) to the rotated rectangles. It depends how you want to handle the overlapping areas, but for the sample if we want to concat the Red rectangle right to the Blue one, we need to add the Blue rectangle Width + the original rectangle Height in the X direction. For other rotated rectangles you can apply similar additional offset to X, Y or both.
To complete the sample, if we modify the code like this
var g = e.Graphics;
var loc = new Point(128, 128);
var rect = new Rectangle(0, 0, 64, 16);
g.ResetTransform();
g.TranslateTransform(loc.X, loc.Y);
g.FillRectangle(Brushes.Blue, rect);
g.ResetTransform();
g.TranslateTransform(loc.X + rect.Width + rect.Height, loc.Y);
g.RotateTransform(90);
g.FillRectangle(Brushes.Red, rect);
g.ResetTransform();
g.TranslateTransform(loc.X + rect.Width + rect.Height, loc.Y + rect.Width + rect.Height);
g.RotateTransform(180);
g.FillRectangle(Brushes.Green, rect);
g.ResetTransform();
g.TranslateTransform(loc.X, loc.Y + rect.Width + rect.Height);
g.RotateTransform(270);
g.FillRectangle(Brushes.Magenta, rect);
the new result will be
Once you understand all that, hope you can apply the required corrections to your concrete code.

Related

Black spots after rotating bitmap c#

I need to rotate an image by a certain angle before further operations. After rotating, im left with black areas on my bitmap.
Image after rotating by 30 degrees
I've managed to find similar issue in java right here.
Is there something like that for c#?
Im using the following code, that i found earlier on stack:
Bitmap Rotate_Image(Bitmap bmp, float angle)
{
Bitmap rotatedImage = new Bitmap(bmp.Width, bmp.Height);
rotatedImage.SetResolution(bmp.HorizontalResolution, bmp.VerticalResolution);
using (Graphics g = Graphics.FromImage(rotatedImage))
{
// Set the rotation point to the center in the matrix
g.TranslateTransform(bmp.Width / 2, bmp.Height / 2);
// Rotate
g.RotateTransform(angle);
// Restore rotation point in the matrix
g.TranslateTransform(-bmp.Width / 2, -bmp.Height / 2);
// Draw the image on the bitmap
g.DrawImage(bmp, new Point(0, 0));
}
return rotatedImage;
}
Since your output is *.png I assume you want to use a transparent background. Just call g.Clear(Color.FromArgb(0, default)); before applying TranslateTransform. Or just set any other background color if you like.
You also can set g.SmoothingMode = SmoothingMode.AntiAlias; to smoothen the sides of the rotated image.

C# - DrawBorder - Bottom and Right side not visible [duplicate]

This question already has answers here:
Pixel behaviour of FillRectangle and DrawRectangle
(3 answers)
Closed 4 years ago.
I want to add a different bordercolor for every side of the element,
yet it's working pretty okay, the only problem I got is that my right side and bottom side of the border isn't visible.
public static void DrawBorder
(
Graphics graphics, Rectangle bounds,
Color leftColor, int leftWidth, ButtonBorderStyle leftStyle,
Color topColor, int topWidth, ButtonBorderStyle topStyle,
Color rightColor, int rightWidth, ButtonBorderStyle rightStyle,
Color bottomColor, int bottomWidth, ButtonBorderStyle bottomStyle
){}
Color leftColor = Color.FromArgb(65,0,0,0), rightColor = Color.FromArgb(150, 0, 0, 0), topColor = Color.FromArgb(65, 0, 0, 0), bottomColor = Color.FromArgb(150, 0, 0, 0);
int leftWidth = 3, rightWidth = 3, topWidth = 3, bottomWidth = 3;
ButtonBorderStyle leftStyle = ButtonBorderStyle.Solid, rightStyle = ButtonBorderStyle.Solid, topStyle = ButtonBorderStyle.Solid, bottomStyle = ButtonBorderStyle.Solid;
private void Paint_(object sender, PaintEventArgs e)
{
Rectangle borderRectangle = this.ClientRectangle;
borderRectangle.Inflate(0, 0);
ControlPaint.DrawBorder(e.Graphics, borderRectangle,
leftColor, leftWidth, leftStyle,
topColor, topWidth, topStyle,
rightColor, rightWidth, rightStyle,
bottomColor, bottomWidth, bottomStyle);
}
I'm using the "Paint_" function for every element you see here, so it's the same problem on every of these.
I'm pretty new to any of the "Draw" stuff, so I don't know anything which could be the problem.
The Draw... calls accepting a Pen instance seem (by default) to draw a rectangle bigger than 1 pixel to the right and bottom. So if you call something like DrawRectangle(Pens.Black, 0, 0, 100, 100), the rectangle on screen will look like as if it spans the coordinates 0, 0 to 101, 101.
The reasoning behind this is described here: Pixel behaviour of FillRectangle and DrawRectangle
To quickly fix your drawing, just pass coordinates smaller by 1 pixel to the right or bottom. E.g., to fix the above example, you'd call DrawRectangle(0, 0, 99, 99) to receive a rectangle spanning the coordinates 0, 0 to 100, 100 on the screen.
I personally resigned from using Pens and Draw calls for bordered rectangles and always use two FillRectangle calls (using Brush instances) as follows:
// Draws a white rectangle with black border
Rectangle rect = new Rectangle(0, 0, 100, 100);
gr.FillRectangle(Brushes.Black, rect); // Draw border
rect.Inflate(-1, -1); // Decrease the size of the rectangle by 1 pixel on all sides
gr.FillRectangle(Brushes.White, rect); // Draw background above it
I have read that FillRectangle is faster than DrawRectangle (as it can simply bitblit the area, unlike Draw which requires to draw for separate lines with all possible shenanigans internally).

Graphics.DrawPath and LinearGradientBrush issue

In relation to this question that I asked a few weeks ago now
LinearGradientBrush does not render correctly
Consider the following code:
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Rectangle rect = new Rectangle(100, 100, 200, 100);
using(LinearGradientBrush brush = new LinearGradientBrush(rect, Color.Red, Color.Blue, 90))
{
using(Pen pen = new Pen(brush, 1))
{
pen.Alignment = PenAlignment.Inset;
e.Graphics.DrawRectangle(pen, rect);
}
}
}
Produces this result...
Why is there a red line where there should be a blue line, and how do I fix this?
Pen.Alignment = PenAlignment.Inset didn't work!
Pens (or the Graphics DrawMethods) have a tendency to draw outside their boundaries. I think Microsoft considered that a feature, but I never understood it.
Try using a smaller rectangle for the pen:
using (var brush = new LinearGradientBrush(rect, Color.Red, Color.Blue, 90)) {
using (Pen pen = new Pen(brush, 1)) {
e.Graphics.DrawRectangle(pen, new Rectangle(rect.X, rect.Y,
rect.Width - 1, rect.Height - 1));
}
}
OK, to sum it up: DrawRectangle always overdraws by 1 pixel (*) and the LinearGradientBrush therefore restarts with the 1st color.
Yes, Lars got one solution, but here is an interesting alternative:
brush.WrapMode = WrapMode.TileFlipXY;
This makes sure that the gradient doesn't start at the beginning when it has to overdraw but reverses in both directions, so the extra pixel is drawn in the right Color and you don't need to manipulate one of the two the Rectangle Sizes..
Well ok, if you need total precision it is probably second best, as the last row and column will have the same color as their neighbours..but not having to deal with two sizes may be worth it..
(*) Which is why you can't use it to draw a 1x1 square/pixel. Instead you need to use FillRectangle..

Pen.Alignment is not working while drawing line

I want to draw a thick line and a thin line. The thick line should be positioned inside of the theoretical line. So I set the pen alignment as below.
Pen blackPen = new Pen(Color.FromArgb(255, 0, 0, 0), 1);
Pen greenPen = new Pen(Color.FromArgb(255, 0, 255, 0), 10);
greenPen.Alignment = PenAlignment.Inset;
e.Graphics.DrawLine(greenPen, 10, 100, 100, 50);
e.Graphics.DrawLine(blackPen, 10, 100, 100, 50);
But the idea is not get worked. Any better idea to do the same ???
Pen.Alignment is partially implemented:
This property determines how the Pen draws closed curves and polygons. The PenAlignment enumeration specifies five values; however, only two values—Center and Inset—will change the appearance of a drawn line. Center is the default value for this property and specifies that the width of the pen is centered on the outline of the curve or polygon. A value of Inset for this property specifies that the width of the pen is inside the outline of the curve or polygon. The other three values, Right, Left, and Outset, will result in a pen that is centered.
So, Inset will work only on polygons or curves (e.g. Graphics.DrawRectangle).

Draw line in C# sometimes has missing parts

I'm currently trying to draw some lines in C# with the Graphics class.
My problem is, that sometimes (mostly on the repainting on resizing the form) some parts of the lines are missing.
This is how it looks like then:
This is my code where I draw the lines:
Graphics g = pnlGraph.CreateGraphics();
g.Clear(pnlGraph.BackColor);
Point p1 = new Point((mainNode.Left + (mainNode.Width / 2)), (mainNode.Top + (mainNode.Height / 2)));
Point p2 = new Point((pic.Left + (pic.Width / 2)), (pic.Top + (pic.Height / 2)));
g.DrawLine(new Pen(new SolidBrush(Color.Black), 2), p1, p2);
This code draws some lines from a mainNode in the middle of my panel to some nodes around it.
I'm calling the function to paint the lines on:
Load,
Resize,
Visible state changed
I also tried it in Paint of the form and the panel which didn't work.
Is there any way to fix it or another way of painting these lines?
Thanks for any answer!
Since the answer of #HansPassant has also made some problems we fixed the problem in another way:
We created an Image and filled it with an rectangle of the size of the panel.
After that we draw the lines in the image and draw the image on the panel.
Graphics g = pnlGraph.CreateGraphics();
Image img = new Bitmap(pnlGraph.Width, pnlGraph.Height);
Graphics gi = Graphics.FromImage(img);
gi.DrawRectangle(new Pen(new SolidBrush(pnlGraph.BackColor)), new Rectangle(0, 0, pnlGraph.Width, pnlGraph.Height));
// For every line:
gi.DrawLine(new Pen(new SolidBrush(Color.Black), 2), p1, p2);
// At the end:
g.DrawImage(img, 0, 0, img.Width, img.Height);

Categories