I'm creating a simple 2d scrolling game as my school project on C#, but I cant seem to find the ratio between the background (platform) and the form height.
here's what I'm trying to do, my form height is 1080, and all of my pictures height are 2160px (double the form) with dpi of 96, I have the background, the floor, and the hero all on different image files so that I can move each one as I want.
I'm trying to get them all to start from the bottom so it would look like this
so I write this code.
void Start()
{
flag = 's';
bg = new Bitmap("bg.bmp");
pf = new Bitmap("platform.png");
player = new Bitmap("idle.png");
y = -(pf.Height-this.ClientSize.Height);
mmy = y;
DrawDubBuff(this.CreateGraphics());
}
void DrawScen(Graphics g)
{
g.Clear(Color.Black);
//SolidBrush br = new SolidBrush(Color.Yellow);
//g.FillRectangle(br, this.Width/2 - this.Height/4, 0, (this.Height/2), this.Height);
if (flag=='m')
{
g.DrawImage(bg, x, y);
g.DrawImage(menu, this.Width/2, this.Height/2);
}
else if (flag == 's')
{
g.DrawImage(bg, x, y);
g.DrawImage(pf, pfx, y);
g.DrawImage(player, mmx, mmy);
//Color pixel = pf.GetPixel(mmx, mmy+10);
MessageBox.Show(""+pf.Height+", "+ this.ClientSize.Height);
//if (pixel.A == 0)
//{
// mmy--;
//}
}
}
void DrawDubBuff(Graphics g)
{
Graphics g2 = Graphics.FromImage(off);
DrawScen(g2);
g.DrawImage(off, 0, 0);
}
but it ends up looking like this
the red square is exactly at half the image size (1080)
even when I change the image size to 1080 and make y=0, it still doesnt fit the form, it always goes beyond the screen size. I spent hours searching but I couldn't find anything that helped. really hope someone can help me with this, thanks in advance ~
UPDATE
this is what happens when I set y=-1080
If memory serves, 0,0 on a winforms/GDI canvas is top left, try setting y to 1080 rather than 0
Related
I'm doing an application with a splash screen.
I've an image an I'd like to put below a progress bar like :
Example
I've succeeded to make the bitmap transparent.
But, now, the image is behind the progress bar
Now
Is there a way to get the image in front of the progress bar ?
Thank you.
F.
Code :
public partial class Form1 : Form
{
Bitmap m_l;
public Form1()
{
InitializeComponent();
m_l = Properties.Resources.LU;
m_l.MakeTransparent(Color.Transparent);
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawImage(m_l, new Rectangle(new Point(0, -40), new Size(200, 264))); progressBar1.Refresh();
}
}
(sorry, for missuing the answer function but the answer is to long for a comment)
#TaW
seems like you didnt quite understand the approach, so I will try to explain it in more detail
OP asked if he can make a transparant Image over another control (a progressbar)
I assumed this transparent Image is inside a PictureBox, you seem to assume some other control
to position the control, if my assumption is correct the picturebox, infront of the progress bar all he has to do is right click and click "Bring to Front" on the PictureBox
and there you have it a "transparent" PictureBox infront of a progressbar - but as you mentioned in your answer we cannot stop there since the "transparent" isnt what I expected, but obviously you knew - its this "parent background color picking" that WinForms does and we end up with a not fully transparent image infront of the ProgressBar but instead one with a gray Background
Now the posted url comes in place:
http://www.richardhyland.com/diary/2009/05/26/how-to-truely-make-a-picturebox-background-transparent/
This is the code provided, and explained in that url:
public static System.Drawing.Drawing2D.GraphicsPath Transparent(Image im)
{
int x;
int y;
Bitmap bmp = new Bitmap(im);
System.Drawing.Drawing2D.GraphicsPath gp = new System.Drawing.Drawing2D.GraphicsPath();
Color mask = bmp.GetPixel(0, 0);
for (x = 0; x <= bmp.Width - 1; x++)
{
for (y = 0; y <= bmp.Height - 1; y++)
{
if (!bmp.GetPixel(x, y).Equals(mask))
{
gp.AddRectangle(new Rectangle(x, y, 1, 1));
}
}
}
bmp.Dispose();
return gp;
}
With this we can achieve a fully transparent Picture box infront of a Progress bar.
So without this Code, we have this:
But with that Code:
Notice, this approach has some downsides:
doesn't work perfectly - as you can see gray pixels around the edges of the image
performs poorly on big Images - since getting each pixel with GetPixel is "challange"
(Please, ignore the fact that the image shows "JPG" and I am talking about transparent Images - this was just the first image Google search presented me and yes, the file is a transparent png)
You can accomplish this using a PictureBox with a Region.
Add a PictureBox to your form. This will hold the image. Position it to overlap the ProgressBar as you would like. Set the Image property to your overlay image.
In the form constructor we're then going to set the Region of this PictureBox. The region defines the shape of the control. We're going to set the Region equal to the non-transparent parts of the image.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
pictureBox1.Region = CreateRegion(Properties.Resources.LU);
}
private static Region CreateRegion(Bitmap maskImage)
{
// We're using pixel 0,0 as the "transparent" color.
Color mask = maskImage.GetPixel(0, 0);
GraphicsPath graphicsPath = new GraphicsPath();
for (int x = 0; x < maskImage.Width; x++)
{
for (int y = 0; y < maskImage.Height; y++)
{
if (!maskImage.GetPixel(x, y).Equals(mask))
{
graphicsPath.AddRectangle(new Rectangle(x, y, 1, 1));
}
}
}
return new Region(graphicsPath);
}
}
Much of this code came from here
There are 5 6 options:
You could set the ProgressBar's BackColor to Transparent. Result:
Translation:
Invalid property value. This control does not support a transparent backcolor.
This will hold true for a subclass as well.
You could nest a transparent Panel with the image as its BackgroundImage. Result:
As you can see, despite the panel and most of the image being transparent, the progressbar still underlays it with a rectangle in its own BackColor; which, see above, can't be transparent.
You could overlay with the panel.
Result:
Looks similar. But this time the backcolor is the original background of wherever the panel was before overlaying it. This is the way winforms fakes transparency; this faked transpareny will only work with nested controls, but not with all..
You could draw your image in the progressbar's Paint event. Problem: It doesn't have one. And if you subclass it it will not work for you.
To sum it up: all those attempts fail; the conclusion is simple: ProgressBar is an animated control that won't support any messing with it.
Last option: Write your own. You can subclass a Panel or Label and write your own progressbar. Many folks who wanted to have a custom look, have done this and you can find many ready made examples.
Upate: Looks like you can have a 6th option, which will work if and only if you don't need semi-transparency, like anti-aliasing etc..: You can create a GraphicsPath to create a Region which will mask some control with the image.. So while my example will not work, OP's image may look quite OK.
as ways, people are developers but seams to have a really weak logic, post code and link the rest to a site that can die at any time, here the 2 missing line of the answer
public static System.Drawing.Drawing2D.GraphicsPath Transparent(Image im)
{
int x;
int y;
Bitmap bmp = new Bitmap(im);
System.Drawing.Drawing2D.GraphicsPath gp = new System.Drawing.Drawing2D.GraphicsPath();
Color mask = bmp.GetPixel(0, 0);
for (x = 0; x <= bmp.Width - 1; x++)
{
for (y = 0; y <= bmp.Height - 1; y++)
{
if (!bmp.GetPixel(x, y).Equals(mask))
{
gp.AddRectangle(new Rectangle(x, y, 1, 1));
}
}
}
bmp.Dispose();
return gp;
use:
System.Drawing.Drawing2D.GraphicsPath gp = Resources.Images.Transparent(pictureBox1.Image);
pictureBox1.Region = new System.Drawing.Region(gp);
It seems like this should be simple enough, but I'm really struggling with finding any documentation on how I can do this. I'm simply looking to crop an image to turn a square into a circle.
There is a lot of discussion about it, but I can't seem to find a good example of how to do this using UWP/Win2D.
Here is a bit of code to illustrate the issue I was trying to describe in my comments:
// draw a 10x10 grid of circles
var bitmap = await CanvasBitmap.LoadAsync(sender, "Assets/ice.png"); // hex-shaped image is 250x220 pixels
var brush = new CanvasImageBrush(sender, bitmap);
for (var i = 0; i < 10; i++)
{
for (var j = 0; j < 10; j++)
{
//_drawingSession.FillCircle(new Vector2(i * 50, j * 50), (float)(25), Colors.Blue);
_drawingSession.FillCircle(new Vector2(i * 50, j * 50), (float)(25), brush);
}
}
The image below shows how the brush is being cut from the same x/y coordinates based on the vector where the target circle is to be drawn.
Note: the same effect occurs with FillEllipse().
You can try to use CanvasImageBrush and CanvasDrawingSession.FillEllipse Method achieve it.
private async void canvas_Draw(Microsoft.Graphics.Canvas.UI.Xaml.CanvasControl sender,
Microsoft.Graphics.Canvas.UI.Xaml.CanvasDrawEventArgs args)
{
using (CanvasBitmap bitmap = await CanvasBitmap.LoadAsync(sender, "Assets/image.jpg"))
{
CanvasImageBrush canvasImageBrush = new CanvasImageBrush(sender, bitmap);
args.DrawingSession.FillEllipse(new System.Numerics.Vector2(100f), 100, 100, canvasImageBrush);
}
}
------------ Update -------------
If you want to cut a circle out of the image source, you can configure the CanvasImageBrush.Transform property to scale the image, then cut the circle and display it on the canvas.
private async void canvas_Draw(Microsoft.Graphics.Canvas.UI.Xaml.CanvasControl sender,
Microsoft.Graphics.Canvas.UI.Xaml.CanvasDrawEventArgs args)
{
using (CanvasBitmap bitmap = await CanvasBitmap.LoadAsync(sender, "Assets/image.jpg"))
{
CanvasImageBrush canvasImageBrush = new CanvasImageBrush(sender, bitmap);
System.Numerics.Vector2 center = new System.Numerics.Vector2((float)(bitmap.Size.Width / 2),
(float)(bitmap.Size.Height / 2));
canvasImageBrush.Transform = System.Numerics.Matrix3x2.CreateScale(0.5F, center);
args.DrawingSession.FillEllipse(center, 160, 160, canvasImageBrush);
}
}
You should change some parameters in my above code to satisfy your requirement, such as the scale in the Matrix3x2.CreateScale method.
Okay, after chatting with one of the fellows on the GitHub Win2D project, I finally have a clear answer on how this works - and it works nothing like I would have expected it to work.
First, the bitmap brush image is by default being positioned at 0,0 on the canvas.
In my case, I wanted to cut a circle from the image and draw it someplace else on the canvas. This requires 2 separate bits of math.
First, you need to position the bitmap's top-left-corner (TLC) to where you want the circle to be drawn. This is done by setting the brush's Transform property. In my example, I'm setting the image TLC to 300/300;
// create the brush
var brush = new CanvasImageBrush(sender, _tiles[1]);
brush.Transform = Matrix3x2.CreateTranslation(300, 300);
Now, to cut/draw the circle using the brush image, I have to describe where the center of the image is to be on the canvas. My image is 250x220.
// 300+250/2, 300+220/2 = 425, 410
_args.DrawingSession.FillCircle(new Vector2(425, 410), (float)(110), brush);
This gives the effect of cutting a circle out of my original bitmap and drawing it on the canvas at the desired location.
Hopefully this is clear enough. I know I certainly struggled to find the answer.
I have a Rectangle (rec) that contains the area in which a smaller image is contained within a larger image. I want to display this smaller image on a Picturebox. However, what I really am doing is using the smaller image as a picture detector for a larger image that is 333x324. So what I want to do is use the coordinates of the smaller image rectangle, and then draw to the Picturebox, starting from lefthand side of the rectangle, going outwards by 333 width and 324 height.
Currently my code works but it only displays the small image that was being used for detection purposes. I want it to display the smaller image + 300 width and + 300 height.
I fiddled with this code for hours and I must be doing something extremely basic wrong. If anyone can help me I would appreciate it so much!
My code for the class:
public static class Worker
{
public static void doWork(object myForm)
{
//infinitely search for maps
for (;;)
{
//match type signature for Threading
var myForm1 = (Form1)myForm;
//capture screen
Bitmap currentBitmap = new Bitmap(CaptureScreen.capture());
//detect map
Detector detector = new Detector();
Rectangle rec = detector.searchBitmap(currentBitmap, 0.1);
//if it actually found something
if(rec.Width != 0)
{
// Create the new bitmap and associated graphics object
Bitmap bmp = new Bitmap(rec.X, rec.Y);
Graphics g = Graphics.FromImage(bmp);
// Draw the specified section of the source bitmap to the new one
g.DrawImage(currentBitmap, 0,0, rec, GraphicsUnit.Pixel);
// send to the picture box &refresh;
myForm1.Invoke(new Action(() =>
{
myForm1.getPicturebox().Image = bmp;
myForm1.getPicturebox().Refresh();
myForm1.Update();
}));
// Clean up
g.Dispose();
bmp.Dispose();
}
//kill
currentBitmap.Dispose();
//do 10 times per second
System.Threading.Thread.Sleep(100);
}
}
}
If I understand correctly, the rec variable contains a rectangle with correct X and Y which identifies a rectangle with Width=333 and Height=324.
So inside the if statement, start by setting the desired size:
rec.Width = 333;
rec.Height = 324;
Then, note that the Bitmap constructor expects the width and height, so change
Bitmap bmp = new Bitmap(rec.X, rec.Y);
to
Bitmap bmp = new Bitmap(rec.Width, rec.Height);
and that's it - the rest of the code can stay the way it is now.
I am attempting to zoom in a picturebox using the mousewheel.
Using the following variables:
public static int offsetX = 0;
public static int offsetY = 0;
public static double scale = .05;
I draw a series of polygons to the picture box. However, I wanted the bottom left corner to refer to 0,, so I draw everything to the form with a -y. The drawn points have been affected by the above variables but the real points stay the same.
void pictureBox1_MouseWheel(object sender, MouseEventArgs e)
{
if (e.Delta > 0)
scale += .025;
else
scale -= .025;
pictureBox1.Invalidate();
}
When the mousewheel is moved forward I increase the scale variable and the box is refreshed. It is repainted using this code in the picturebox paint method:
Graphics g = e.Graphics;
foreach (Member m in activeTruss.members)
{
if (m.Visible == true)
{
Point[] pointArray = new Point[m.poly.Points.Count()];
int index = 0;
foreach (System.Windows.Point p in m.poly.Points)
{
pointArray[index].X = (int)((p.X + offsetX) * scale);
pointArray[index].Y = (int)-((p.Y + offsetY) * scale);
index++;
}
SolidBrush myBrush = new SolidBrush(m.color);
g.FillPolygon(myBrush, pointArray);
}
}
it zooms the correct amount, however it appears to zoom towards the upper left corner because the offsets stay the same. The opposite is true when zooming out. How should I edit the offsets as I turn the mouse wheel in order to zoom directly towards the point under my mouse?
If you want to center your zoom
double offsetX = scale/2
double offsetY = scale/2
Update
To answer your second part about flipped picture, it sounds like you are not making a distinction on the x,y of your picture vs the x,y screen coordinates. Usually, screen coordinates start on the top of the screen, so top left is 0,0, however when you draw your picture, your picture's 0,0 is on the bottom left so you use -y. What you want to do is to start drawing from 0,0 to 0,MAXY without the flip. For this implementation detail, your code would help alot hehe :)
What I want to do is basically cropping a rectangle from an image. However, it should satisfy some special cases:
I want to crop an angled rectangle on image.
I don't want to rotate the image and crop a rectangle :)
If cropping exceeds the image size, I don't want to crop an empty background color.
I want to crop from back of the starting point, that will end at starting point when rectangle size completed. I know I couldn't explain well so if I show what I want visually:
The blue dot is the starting point there, and the arrow shows cropping direction. When cropping exceeds image borders, it will go back to the back of the starting point as much as, when the rectangle width and height finished the end of the rectangle will be at starting point.
Besides this is the previous question I asked:
How to crop a cross rectangle from an image using c#?
In this question, I couldn't predict that a problem can occur about image dimensions so I didn't ask for it. But now there is case 3. Except case three, this is exactly same question. How can I do this, any suggestions?
What needs to be done is to add offsets to the matrix alignment. In this case I am taking one extra length of the rectangle from each side (total 9 rectangles) and offsetting the matrix each time.
Notice that it is necessary to place offset 0 (the original crop) last, otherwise you will get the wrong result.
Also note that if you specify a rectangle that is bigger than the rotated picture you will still get empty areas.
public static Bitmap CropRotatedRect(Bitmap source, Rectangle rect, float angle, bool HighQuality)
{
int[] offsets = { -1, 1, 0 }; //place 0 last!
Bitmap result = new Bitmap(rect.Width, rect.Height);
using (Graphics g = Graphics.FromImage(result))
{
g.InterpolationMode = HighQuality ? InterpolationMode.HighQualityBicubic : InterpolationMode.Default;
foreach (int x in offsets)
{
foreach (int y in offsets)
{
using (Matrix mat = new Matrix())
{
//create the appropriate filler offset according to x,y
//resulting in offsets (-1,-1), (-1, 0), (-1,1) ... (0,0)
mat.Translate(-rect.Location.X - rect.Width * x, -rect.Location.Y - rect.Height * y);
mat.RotateAt(angle, rect.Location);
g.Transform = mat;
g.DrawImage(source, new Point(0, 0));
}
}
}
}
return result;
}
To recreate your example:
Bitmap source = new Bitmap("C:\\mjexample.jpg");
Bitmap dest = CropRotatedRect(source, new Rectangle(86, 182, 87, 228), -45, true);