I'm working on an application that has a graphic editor. Aside from some other graphic components the main feature are some shapes (rectangles, triangles, stars etc.). The thing I would like to do is to have the ability to resize them after a double click, so there should be a container shown with points that can be dragged to resize the shape. There are many great tutorials out in the internet but mainly for rectangles or for other shapes that are "packed" into rectangle viewboxes.
The issue is that I need to have my resize points exactly on the vertexes, so for example I can't have a triangle inside a rectangle viewbox, but I need exactly three points - one on every vertex. The same applies for the other shapes like stars and arrows which are much more complicated.
Here's what I mean:
So I think I have two ways. Either pass a dynamic list of points after a double click and display them as separate shapes or binding them with my shape inside my shape class, but I cannot figure out how to add multiple shapes to a viewbox so that they keep their abilities. Here is a simplified snippet of how my shape classes look like:
public class RectangleObject : ShapeObject
{
private Rectangle _rectangle;
private Viewbox _viewbox;
public RectangleObject(Color fillColor)
{
_rectangle = new Rectangle()
{
Fill = new SolidColorBrush(fillColor),
Stretch = Stretch.Fill
};
_viewbox.child = _rectangle;
}
public void SetDimensions(){}
//... and some other methods
}
A nice solution would be if the viewbox could contain my shape and the resize points but I will appreciate any advice. I know that a canvas would be a better solution but all other components are packed in viewboxes so it would be problematic because of inheritance and would need many changes. Thanks in advance!
Yes I know exactly what you mean. I used CorelDraw back in the day and then Adobe Illustrator and both had the concept of shape transformation mode (your image on the right) as well as vertex edit mode (your image on the left). UWP is similar to WPF and WPF has a concept of adorners which you can customise to do whatever you want including what I just described.
So when you enter one of these modes, rather than modify your existing shape to show selectors; instead you create adorners that are superimposed over the shape. That way one doesn't clobber the other and you may have custom behavior for each as you indicated.
See also
Adorners - MSDN, https://msdn.microsoft.com/en-us/library/ms743737(v=vs.110).aspx, retrieved 2017-1-12
Related
This is more of a "Is it possible (with a reasonable amount of time and work)" than a "how exactly is it possible" question. I'm getting into WPF at the moment and am interested in graphical applications in an MVVM approach. In the meaning of an ms-paint like application. Now I see that and how I can draw e.g. a ractangle on a canvas, store those rectangles in a list etc.
But I am wondering if I can do that more advanced. For example extend the rectangle so I can give it more infos (I can't extend the rectangle itself since it's a sealed class), have existing shapes on the canvas able to drag them around, make the shapes complex (e.g. I double click one to open a new Window that represents the "inside" of that shape) etc.
Is such an application possible with a reasonable amount of work and time in WPF or would I rather use some different library/framework for this?
Yes, It is possible, Actually, you are listing CAD specifications, In fact, I work on this type of technology, so I'll suggest you some resources to have a clue..
Take a look at this project(WPF, 2D)
And this one(WPF, 3D)
And this one(WPF, 2D)
The previous projects are WPF-based, also, you might host a WinForm control in your WPF app, take a look at this one(WinForms, 2D)
If you change the specification a bit and say: "I don't want to edit the drawings on the canvas", then you could go with this option: convert your shapes to PathFigureCollection and EllipseGeometry objects, then construct Paths from these objects and add the Paths to the Canvas, this is a pure WPF approach. Indeed, you can add traditinal controls like TextBlocks as children to your Canvas, I have done such one like this..
Hope it helps.
I was doing a game project in Windows Forms and really loved how it turned out, except for one thing that was bugging me: the new picturebox's I am adding are "eating" away from the one behind it, showind the background of its parent and not showing the image behind him, as I thought it will. Apparently that's how transparency works in Windows Forms, it copies the colors behind him, basically.
This is how it looks, and I want the animals to be seen fully.
I also tried this from another post here, but it turned out like this.
There might be no solution to this, I have other things in this little game I made. There is another picturebox with other buttons and stuff, that represents the shop. And also you can see in both images that there is a pannel in the bottom section with some details. In that case, I would leave it as it is and maybe try another time to move it to WPF.
=================== EDIT ===================
The accepted answer helped me switch from a game with overlaying PictureBoxes to a game where I "paint" each frame of the game on the background. Check that answer's comment for more details about this :) This is how it turned out.
This is specifically for my code, where I have a static Resources class. Yours could look a lot cleaner, maybe you have this Render function where you have every other rectangle and image. I hope this helps everyone that visits this page :)
// ================ SOLUTION ================
public static void Render()
{
//draw the background again. This is efficient enough, maybe because the pixels that did not changed won't be redrawn
grp.DrawImage(Resources.gameBackground, 0, 0);
//draw the squirrel image on the position and length of the "squirrel" Rectangle
grp.DrawImage(Resources.currentSquirrelImage, Resources.squirrel.X, Resources.squirrel.Y, Resources.squirrel.Width, Resources.squirrel.Height);
//after that, draw each projectile (acorns, wallnuts) the same way
foreach (Projectile projectile in Resources.projectiles)
{
grp.DrawImage(projectile.image, projectile.rect.X, projectile.rect.Y, projectile.rect.Width, projectile.rect.Height);
}
//then draw each animal
foreach (Enemy animal in Resources.enemies)
{
grp.DrawImage(animal.image, animal.rect.X, animal.rect.Y, animal.rect.Width, animal.rect.Height);
}
//and finally, the image that shows where the squirrel is shooting
grp.DrawImage(Resources.selectionImge, Resources.selection.X, Resources.selection.Y, Resources.Selection.Width, Resources.Selection.Height);
//update the image of the game picturebox
form.TheGame.Image = bmp;
}
As you have noticed .net control transparency is not real transparency, it copies it's parent background, so if you have other sibiling controls the one with the higher Z index will occlude the others.
If you want to create a game avoid the usage of picture boxes, there are many options: use a game engine like Unity or roll your own.
Something easy to do is to create a Bitmap, render your game in it and then present it in your form, but beware, that can be slow.
EDIT: As you requested here is an example on how to use the Intersect function of the Rectangle struct to determine which parts of two rectangles overlap.
Rectangle R1 = new Rectangle (0,0,32,32);
Rectangle R2 = new Rectangle (16,16,32,32);
//To test if a rectangle intersects with another...
bool intersects = R1.IntersectsWith(R2); //If does not intersect then there's nothing to update
//To determine the area that two rectangles intersect
Rectangle intersection = Rectangle.Intersect(R1, R2); //In this example that would return a rectangle with (16,16,16,16).
I'm trying to make something similar to paint. I'm trying to figure out how make different brush styles. Like in Paint 3D you get a certain line fills when using the pen tool vs using the paint brush tool.
I have no idea where to even start. I've spent a good portion of the day looking through documentations, and watching YouTube videos. I'm more lost than when I started. The closest thing I came across was line caps, but that's definitely not what I'm looking for.
!!See the UPDATE below!!
Hans' link should point you in the right direction, namely toward TextureBrushes.
To help you further here a few points to observe:
TextureBrush is a brush, not a pen. So you can't follow a path, like the mouse movements to draw along that curve. Instead, you need to find an area to fill with the brush.
This also implies that you need to decide how and when to trigger the drawing; basic options are by time and/or by distance. Usually, the user can set parameters for these often called 'flow' and 'distance'..
Instead of filling a simple shape and drawing many of those, you can keep adding the shapes to a GraphicsPath and fill that path.
To create a TextureBrush you need a pattern file that has transparency. You can either make some or download them from the web where loads of them are around, many for free.
Most are in the Photoshop Brush format 'abr'; if they are not too recent (<=CS5) you can use abrMate to convert them to png files.
You can load a set of brushes to an ImageList, set up for large enough size (max 256x256) and 32bpp to allow alpha.
Most patterns are black with alpha, so if you want color you need to create a colored version of the current brush image (maybe using a ColorMatrix).
You may also want to change its transparency (best also with the ColorMatrix).
And you will want to change the size to the current brush size.
Update
After doing a few tests I have to retract the original assumption that a TextureBrush is a suitable tool for drawing with textured tips.
It is OK for filling areas, but for drawing free-hand style it will not work properly. There are several reasons..:
one is that the TextureBrush will always tile the pattern in some way, flipped or not and this will always look like you are revealing one big underlying pattern instead of piling paint with several strokes.
Another is that finding the area to fill is rather problematic.
Also, tips may or may not be square but unless you fill with a rectangle there will be gaps.
See here for an example of what you don't want at work.
The solution is really simple and much of the above still applies:
What you do is pretty much regular drawing but in the end, you do a DrawImage with the prepared 'brush' pattern.
Regular drawing involves:
A List<List<Point>> curves that hold all the finished mouse paths
A List<Point> curentCurve for the current path
In the Paint event you draw all the curves and, if it has any points, also the current path.
For drawing with a pattern, it is necessary to also know when to draw which pattern version.
If we make sure not to leak them we can cache the brush patterns..:
Bitmap brushPattern = null;
List<Tuple<Bitmap,List<Point>>> curves = new List<Tuple<Bitmap,List<Point>>>();
Tuple<Bitmap, List<Point>> curCurve = null;
This is a simple/simplistic caching method. For better efficiency you could use a Dictionary<string, Bitmap> with a naming scheme that produces a string from the pattern index, size, color, alpha and maybe a rotation angle; this way each pattern would be stored only once.
Here is an example at work:
A few notes:
In the MouseDown we create a new current curve:
curCurve = new Tuple<Bitmap, List<Point>>(brushPattern, new List<Point>());
curCurve.Item2.Add(e.Location);
In the MouseUp I add the current curve to the curves list:
curves.Add(new Tuple<Bitmap, List<Point>>(curCurve.Item1, curCurve.Item2.ToList()));
Since we want to clear the current curve, we need to copy its points list; this is achieved by the ToList() call!
In the MouseMove we simply add a new point to it:
if (e.Button == MouseButtons.Left)
{
curCurve.Item2.Add(e.Location);
panel1.Invalidate();
}
The Paint goes over all curves including the current one:
for (int c = 0; c < curves.Count; c++)
{
e.Graphics.TranslateTransform(-curves[c].Item1.Width / 2, -curves[c].Item1.Height / 2);
foreach (var p in curves[c].Item2)
e.Graphics.DrawImage(curves[c].Item1, p);
e.Graphics.ResetTransform();
}
if (curCurve != null && curCurve.Item2.Count > 0)
{
e.Graphics.TranslateTransform(-curCurve.Item1.Width / 2, -curCurve.Item1.Height / 2);
foreach (var p in curCurve.Item2)
e.Graphics.DrawImage(curCurve.Item1, p);
e.Graphics.ResetTransform();
}
It makes sure the patterns are drawn centered.
The ListView is set to SmallIcons and its SmallImageList points to a smaller copy of the original ImageList.
It is important to make the Panel Doublebuffered! to avoid flicker!
Update: Instead of a Panel, which is a Container control and not really meant to draw onto you can use a Picturebox or a Label (with Autosize=false); both have the DoubleBuffered property turned on out of the box and support drawing better than Panels do.
Btw: The above quick and dirty example has only 200 (uncommented) lines. Adding brush rotation, preview, a stepping distance, a save button and implementing the brushes cache takes it to 300 lines.
I'm making a graphics editor for my class project and i want to make so that when, for example a user loads a picture in to the editor or or draw something in the PictureBox, all the alpha parts are shown the chessboard like background.
My idea is that when I create a PictureBox with transparent background set, I create another one behind it, set its BackColor to white and add grey images 50x50, alternately horizontally and vertically. Is that a good approach to the problem? If, not do You have any suggestions?
In Photoshop, for example, I create image 1600x1600. When I zoom to a certain level, it shrinks the boxes and adds more of them to fill the image. If You'we used Photoshop of similar program you know what I mean. Now, how would I go about achieving the same effect?
Creating a Photoshop-like program is a fun project.
There will be many challenges along your way and it is well worth thinking ahead a little..
Here is a short and incomplete list of things to keep in mind:
Draw- and paint actions
Undo, redo, edit
Multiple layers
Zooming and scrolling
Saving and printing
So getting a checkerboard background is only the start of a long journey..
Using a PictureBox as the base canvas is a very good choice, as its several layers will help. Here is a piece of code that will provide you with a flexible checkerboard background, that will keep its size even when you scale the real graphics:
void setBackGround(PictureBox pb, int size, Color col)
{
if (size == 0 && pb.BackgroundImage != null)
{
pb.BackgroundImage.Dispose();
pb.BackgroundImage = null;
return;
}
Bitmap bmp = new Bitmap(size * 2, size * 2);
using (SolidBrush brush = new SolidBrush(col))
using (Graphics G = Graphics.FromImage(bmp) )
{
G.FillRectangle(brush, 0,0,size, size);
G.FillRectangle(brush, size,size, size, size);
}
pb.BackgroundImage = bmp;
pb.BackgroundImageLayout = ImageLayout.Tile;
}
Load an Image for testing and this is what you'll get, left normal, right zoomed in:
Yes, for saving this background should be removed; as you can see in the code, passing in a size = 0 will do that.
What next? Let me give you a few hints on how to approach the various tasks from above:
Scrolling: Picturebox can't scroll. Instead place it in a Panel with AutoScroll = true and make it as large as needed.
Zooming: Playing with its Size and the SizeMode will let you zoom in and out the Image without problems. The BackgroundImage will stay unscaled, just as it does in Photoshop. You will have to add some more code however to zoom in on the graphics you draw on top of the PB or on the layers. The key here is scaling the Graphics object using a Graphics.MultiplyTransform(Matrix).
Layers: Layers are imo the single most useful feature in PhotoShop (and other quality programs). They can be achieved by nesting transparent drawing canvases. Panels can be used, I prefer Labels. If each is sitting inside the one below it and the one at the bottom has the PB as its Parent, all their contents will be shown combined.
Don't use the Label directly but create a subclass to hold additional data and know-how!
Changing their order is not very hard, just keep the nested structure in mind and intact!
Hiding a layer is done by setting a flag and checking that flag in the painting actions
Other data can include a Name, Opacity, maybe an overlay color..
The layers should also be shown in a Layers Palette, best by creating a thumbnail and inserting a layer userobject in a FlowLayoutPanel
Draw Actions: These are always the key to any drawing in WinForms. When using the mouse to draw, each such activity creates an object of a DrawAction class you need to design, which holds all info needed to do the actual drawing, like:
Type (Rectangle, filledRectangle, Line, FreeHandLine (a series of Points), Text, etc.etc..)
Colors
Points
Widths
Text
The layer to draw on
maybe even a rotation
Along with the LayerCanvas class the DrawAction class will be the most important class in the project, so getting its design right is worth some work!
Only the topmost layer will receive the mouse events. So you need to keep track which layer is the active one and add the action to its actions list. Of course the active layer must also be indicated in the Layers Palette.
Since all drawing is stored in List(s), implementing a unlimited undo and redo is simple. To allow for effective drawing and undo, maybe a common action list and an individual list for each layer is the best design..
Undo and Redo are just matter of removing the last list element and pushing it onto a redo-stack.
Editing actions is also possible, including changing the parameters, moving them up or down the actions list or removing one from the middle of the list. It help to show an Actions Palette, like F9 in PhotoShop.
To flatten two or more layers together all you need is to combine their action lists.
To flatten all layers into the Image you only need to draw them not onto their canvas but into the Image. For the difference of drawing onto a control or into a Bitmap see here! Here we have the PictureBox.Image as the second level of a PB's structure above the Background.Image. (The 3rd is the Control surface, but with the multiple layers on top we don't really need it..)
Saving can be done by either by Image.Save() after flattening all Layers or after you have switched off the BackgroundImage by telling the PB to draw itself into a Bitmap ( control.DrawToBitmap() ) which you can then save.
Have fun!
I am trying to create some custom buttons or user controls as shown in the proposed GUI. The functionality should be as follows:
The graphs or configurations are created graphically.
The controls can be dragged from a toolbar or inserted by right mouse click/dropdown
By dragging from one control to another, they should be connected by lines
A toggle should shift the view from controls with options to a simple view
GUI view - controls with options:
GUI view - minimized:
Which functionality in Windows forms can I use to create the connecting lines ?
If they are created by using functionality to draw lines, how can I make sure the controls snap to the line? ..
I am programming in C# with Visual Studio 2010 Express.
Ok. This is a slight modification of the example I created for A similar requirement
My intention is to show that winforms is no longer an option for anyone who needs a serious UI.
The original sample was created in 3 man hours.
You might be surprised to know that the container that holds all these items (both nodes and connectors) is actually a ListBox.
Things worth noting:
The "NodeXX" text is contained within a Thumb control, which enables clicking and dragging.
The connectors can also be selected and show a nice animation when they are.
The left panel allows edition of the currently selected object's values.
The functionality of the UI is completely decoupled from the data that comprises it. Therefore all this nodes and connectors are simple classes with simple int and double properties that can be loaded/saved from a DB or whatever other data source.
If you dislike the way click sequences are done do draw nodes and connectors, that can be perfectly adapted to your needs.
WPF rules.
Edit:
Second version, this time much more similar to your original screenshot:
I added the concept of SnapSpot into the equation. These are the little red semi-circles you see around the nodes, which are actually what the Connectors are tied to.
I also changed the Connector DataTemplate to use a QuadraticBezierSegment based on
Connector.Start.Location,
Connector.MidPoint, and
Connector.End.Location
This allows curved lines to be used as connectors, not just straight lines.
There's a little red-square-shaped Thumb that will appear when you select (click) on a Connector, (visible in the screenshot) that will allow you to move the MidPoint of the curve.
You can also manipulate that value by rolling the mouse wheel when hovering the TextBoxes under "Mid Point" in the left panel.
The "Collapse All" CheckBox allows to toggle between full and small boxes, as shown in the screenshot.
The SnapSpots have an OffsetX OffsetY between 0 and 1 that corresponds to their position relative to the parent Node. These are not limited to 4 and could actually be any number of them per Node.
The ComboBoxes and Buttons have no functionality, but it's just a matter of creating the relevant properties and Commands in the Node class and bind them to that.
Edit2:
Updated download link with a much nicer version.
Edit 10/16/2014: Since a lot of people seem to be interested in this, I uploaded the source to GitHub.
I'm guessing this is a graph type problem. The nodes are the rooms and the edges are the lines that connect the rooms. You can introduce another class (say Connection class) that describes how nodes are connected to edges. For example, your hall connects to a bedroom, not necessarily using a straight line. The Graphics.DrawBezier allows you to draw curved lines, but requires an array of points. This is where the the Connection class comes in. Some code may help...
class Room
{
public Room(String name, Point location);
public void Draw(Graphics g);
}
class Connection
{
public void Add(Point ptConnection);
public void Add(Point[] ptConnection);
// Draw will draw a straight line if only two points or will draw a bezier curve
public void Draw(Graphics g);
}
class House // basically a graph
{
public void Add(Room room);
public void AddRoomConnection(Room r1, Room r2, Connection connector);
// draw, draw each room, then draw connections.
public void Draw(Graphics g);
}
void Main()
{
House myHouse = new House();
Room hall = new Room("Hall", new Point(120,10);
Room bedroom1 = new Room("Bedroom1", Point(0, 80));
Connection cnHallBedroom = new Connection();
cn.Add(new Point()); // add two points to draw a line, 3 or more points to draw a curve.
myHouse.AddRoomConnection(hall, bedroom1, cnHallBedroom);
}
This is basic approach, maybe not the best but might serve as a starting point.