zoom in/out and rotate dynamically created image in windows phone - c#

I am adding images in canvas dynamically on button click and translating these images by using following code:
private void Image_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
Image m = new Image();
m.Source = (sender as Image).Source;
m.Height = 110; m.Width = 110;
wid = Convert.ToInt16(canvas1.ActualWidth - m.Width);
hit = Convert.ToInt16(canvas1.ActualHeight - m.Height);
AddManipulableElement(m);
}
private void AddManipulableElement(UIElement element)
{
ManipulableContainer container = new ManipulableContainer();
container.Content = element;
canvas1.Children.Add(container);
}
public class ManipulableContainer : ContentControl
{
private CompositeTransform _transform;
public ManipulableContainer()
{
this.Loaded += ManipulableContainer_Loaded;
}
private void ManipulableContainer_Loaded(object sender, EventArgs e)
{
_transform = new CompositeTransform();
this.RenderTransform = _transform;
}
protected override void OnManipulationStarted(ManipulationStartedEventArgs e)
{
base.OnManipulationStarted(e);
e.Handled = true;
}
protected override void OnManipulationDelta(ManipulationDeltaEventArgs e)
{
base.OnManipulationDelta(e);
_transform.TranslateX += e.DeltaManipulation.Translation.X;
_transform.TranslateY += e.DeltaManipulation.Translation.Y;
if (_transform.TranslateX > wid)
{
_transform.TranslateX = wid;
}
if (_transform.TranslateY > hit)
{ _transform.TranslateY = hit; }
if (_transform.TranslateY < 0)
{ _transform.TranslateY = -_transform.TranslateY; }
if (_transform.TranslateX < 0)
{ _transform.TranslateX = -_transform.TranslateX; }
e.Handled = true;
}
protected override void OnManipulationCompleted(ManipulationCompletedEventArgs e)
{
base.OnManipulationCompleted(e);
e.Handled = true;
}
}
Everything is working fine . Now I want to add zoom in/out and rotate function to those images by using fingers .

You can use this library for multiple functions: https://multitouch.codeplex.com
Anyway you can use this post as reference : How to zoom in and zoom out Images in WP7?

Related

Drag and Drop Object onto Canvas with coordinates

I managed to drag and drop items from my ListView onto a canvas and show an image on it. I used this question as a template:
https://social.msdn.microsoft.com/Forums/en-US/cef5c42c-87a0-4e19-afc8-935284607488/drag-and-drop-controls-issue-from-listbox-into-canvas-wpf?forum=wpf
I also added the suggestion in that thread, so that the Item gets rendered where I drop it. These are the code behinds for my "Drawing Plate" (The canvas) and the ListView:
Canvas:
public partial class DrawingPlateUC : UserControl
{
IMessenger messenger = Messenger.Instance;
public DrawingPlateUC()
{
InitializeComponent();
}
void Canvas_Drop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent("MyFormat"))
{
var module = e.Data.GetData("MyFormat") as Module;
Canvas CanvasView = sender as Canvas;
Image image = new Image();
image.Source = module.ModuleImage;
CanvasView.Children.Add(image);
}
}
private void Canvas_DragOver(object sender, DragEventArgs e)
{
// write down this point to a private member
Point enterPoint = e.GetPosition(this.moduleCanvas);
messenger.Send<Point>(enterPoint, MessengerTopics.MousePoint);
}
void Canvas_DragEnter(object sender, DragEventArgs e)
{
if (!(e.Data.GetDataPresent("contact")) || (sender == e.Source))
{
e.Effects = DragDropEffects.Copy;
}
}
}
ListView:
public partial class ItemListViewUC : UserControl
{
IMessenger messenger = Messenger.Instance;
Point startPoint;
Point enterPoint;
public ItemListViewUC()
{
messenger.Register<Point>(this, MessengerTopics.MousePoint, GetEnterPoint);
InitializeComponent();
}
private void GetEnterPoint(Point point)
{
enterPoint = point;
}
void StackPanel_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
startPoint = e.GetPosition(null);
}
void StackPanel_PreviewMouseMove(object sender, MouseEventArgs e)
{
Point mousPos = e.GetPosition(null);
Vector diff = startPoint - mousPos;
if ((e.LeftButton == MouseButtonState.Pressed) && (Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance) && (Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance))
{
ListView listView = sender as ListView;
ListViewItem listViewItem = FindAnchestor<ListViewItem>((DependencyObject)e.OriginalSource);
if (listViewItem == null) { return; }
var contact = (Module)listView.ItemContainerGenerator.ItemFromContainer(listViewItem);
DataObject dataObject = new DataObject("MyFormat", contact);
try
{
DragDrop.DoDragDrop(listViewItem, dataObject, DragDropEffects.Copy);
}
catch { }
// Set the Margin property to place the drag item on the canvas.
listViewItem.Margin = new Thickness(enterPoint.X, enterPoint.Y, 0, 0);
}
}
static T FindAnchestor<T>(DependencyObject current) where T : DependencyObject
{
do
{
if (current is T)
{
return (T)current;
}
current = VisualTreeHelper.GetParent(current);
}
while (current != null);
return null;
}
}
This here is supposed to draw the Image on the spot where I dropped it:
listViewItem.Margin = new Thickness(enterPoint.X, enterPoint.Y, 0, 0);
But it only renders on the top left corner, coordinates 0, 0 of the canvas. This is for all Items I drop, they overlay on that position. I already checked the coordinates, they are not 0, 0, but the ones where my mouse is when I drop the item.
This is my Window:
when you drop an item, you don't set any coordinate for Image:
void Canvas_Drop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent("MyFormat"))
{
var module = e.Data.GetData("MyFormat") as Module;
Canvas CanvasView = sender as Canvas;
Image image = new Image();
image.Source = module.ModuleImage;
image.SetValue(Canvas.LeftProperty, _enterPoint.X);
image.SetValue(Canvas.TopProperty, _enterPoint.Y);
CanvasView.Children.Add(image);
}
}
private Point _enterPoint;
private void Canvas_DragOver(object sender, DragEventArgs e)
{
_enterPoint = e.GetPosition(this.moduleCanvas);
messenger.Send<Point>(_enterPoint, MessengerTopics.MousePoint);
}

After adding label to picturebox contols, events don't fire

I'm having a weird behavior with a class I created inheriting from PictureBox.
It's a class made to behave like a button (basically what I care about is the mouse enter, mouse leave, mouse down, mouse up events).
Everything works perfectly until I add the TextLabel (code below) to the control of my customized class. It shows the label, centered and everything as I wanted, but the events I mentioned before (and every other event in that matter) becomes disabled, for some reason it won't fire them.
I would like to know what is the reason for that behavior and if there is any fix for it.
public class RoundedButton : PictureBox
{
private readonly Image r_BasicImage = RoundedButtonCheck2.Properties.Resources.basicRoundedButtonIcon as Image;
private readonly Image r_HoverImage = RoundedButtonCheck2.Properties.Resources.hoverRoundedButtonIcon as Image;
private readonly Image r_ClickImage = RoundedButtonCheck2.Properties.Resources.clickRoundedButtonIcon as Image;
private string m_Text;
private Font m_Font;
public Color m_TextColor;
private Label LabelText = new Label();
public RoundedButton()
{
this.Width = 130;
this.Height = 40;
this.Image = r_BasicImage;
this.BackColor = Color.Transparent;
this.SizeMode = PictureBoxSizeMode.StretchImage;
this.MouseDown += RoundedButton_MouseDown;
this.MouseUp += RoundedButton_MouseUp;
this.MouseEnter += RoundedButton_MouseEnter;
this.MouseLeave += RoundedButton_MouseLeave;
LabelText.Font = ButtonFont;
ButtonTextColor = Color.Black;
//PROBLEMATIC CODE HERE:
***********this.Controls.Add(LabelText);***************
}
public Color ButtonTextColor
{
get
{
return m_TextColor;
}
set
{
m_TextColor = value;
LabelText.ForeColor = m_TextColor;
}
}
public Font ButtonFont
{
get
{
if (m_Font == null)
{
m_Font = new Font("Calibri Light", 12);
}
return m_Font;
}
set
{
m_Font = value;
LabelText.Font = ButtonFont;
adjustLabel();
}
}
public string ButtonText
{
get
{
return m_Text;
}
set
{
m_Text = value;
LabelText.Text = m_Text;
adjustLabel();
}
}
private void adjustLabel()
{
const int MARGIN = 10;
LabelText.AutoSize = true;//needed for autosize calculation of the label;
Size newSize = new Size(LabelText.Size.Width, LabelText.Size.Height); ;
LabelText.AutoSize = false;//after auto-calculated size of the label, set to false in order for centering label works well.
this.MinimumSize = newSize;
this.Size = new Size(newSize.Width + MARGIN, newSize.Height + MARGIN);
LabelText.TextAlign = ContentAlignment.MiddleCenter;
LabelText.Dock = DockStyle.Fill;
}
private void RoundedButton_MouseLeave(object sender, EventArgs e)
{
RoundedButton hoveredButton = sender as RoundedButton;
if (hoveredButton != null)
{
hoveredButton.Image = r_BasicImage;
hoveredButton.SizeMode = PictureBoxSizeMode.StretchImage;
}
}
private void RoundedButton_MouseEnter(object sender, EventArgs e)
{
RoundedButton hoveredButton = sender as RoundedButton;
if (hoveredButton != null)
{
hoveredButton.Image = r_HoverImage;
hoveredButton.SizeMode = PictureBoxSizeMode.StretchImage;
}
}
private void RoundedButton_MouseUp(object sender, MouseEventArgs e)
{
RoundedButton clickedButton = sender as RoundedButton;
if (clickedButton != null)
{
clickedButton.Image = r_BasicImage;
clickedButton.SizeMode = PictureBoxSizeMode.StretchImage;
}
}
private void RoundedButton_MouseDown(object sender, MouseEventArgs e)
{
RoundedButton clickedButton = sender as RoundedButton;
if (clickedButton != null)
{
clickedButton.Image = r_ClickImage;
clickedButton.SizeMode = PictureBoxSizeMode.StretchImage;
}
}
}

Set location of an object as same as cursor postion in visual c#

Well ,I'm trying to make my button location as same as cursor position when the mouse left button is down so i write this :
private void button1_MouseDown(object sender, MouseEventArgs e)
{
button1.Location = Cursor.Position;
}
But the button moves so far than the position of cursor, also it occurs only once and I can't move button freely with the mouse.
What is the problem?
illustrate my comment:
private bool _isAllowMove = false;
...
button1.MouseMove += new MouseEventHandler((object sender, MouseEventArgs e) =>
{
if(!_isAllowMove) {
return;
}
button1.Location = this.PointToClient(Cursor.Position);
});
button1.MouseDown += new MouseEventHandler((object sender, MouseEventArgs e) =>
{
_isAllowMove = true;
});
button1.MouseUp += new MouseEventHandler((object sender, MouseEventArgs e) =>
{
_isAllowMove = false;
});
// other full example for new comment
Dynamically set events for all buttons:
public partial class Form1: Form
{
public Form1()
{
InitializeComponent();
//...
setHandler(button1);
setHandler(button2);
//...
}
protected void setHandler(Button btn)
{
// TODO: synchronise thread & remove old handler
/**
* e.g.:
* lock(_eLock){
* btn.MouseMove -= new MouseEventHandler(..)
* btn.MouseMove += new MouseEventHandler(..)
* }
*
*/
// NOTE: the 'AllowDrop' property only for example -
// you can replace this with your custom components - e.g. ButtonCustom()
/**
* public class ButtonCustom: Button
* {
* ...
* bool AllowMove { get; set; }
* ...
* }
*
*/
btn.AllowDrop = false;
btn.MouseMove += new MouseEventHandler((object sender, MouseEventArgs e) => {
if(!btn.AllowDrop) {
return;
}
btn.Location = this.PointToClient(Cursor.Position);
});
btn.MouseDown += new MouseEventHandler((object sender, MouseEventArgs e) => {
btn.AllowDrop = true;
});
btn.MouseUp += new MouseEventHandler((object sender, MouseEventArgs e) => {
btn.AllowDrop = false;
});
}
}

Keys do not work while using Keys.Down (Or up, left, right)

I am a beginner at C# (C Sharp) and I couldn't figure out why my Arrow keys would not work. Can anyone help me? Note: I am a beginner, I have been working at this for a while now and I can't figure it out. I have tried researching it with no luck, I hope I don't bother you. When I try and move it it doesn't work.
Here is my Form1
public partial class Form1 : Form
{
Graphics paper;
Snake snake = new Snake();
bool left = false;
bool right = false;
bool down = false;
bool up = false;
public Form1()
{
InitializeComponent();
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
paper = e.Graphics;
snake.drawSnake(paper);
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Down && up == false)
{
down = true;
up = false;
right = false;
left = false;
}
if (e.KeyData == Keys.Up && down == false)
{
down = false;
up = true;
right = false;
left = false;
}
if (e.KeyData == Keys.Right && left == false)
{
down = false;
up = false;
right = true;
left = false;
}
if (e.KeyData == Keys.Left && right == false)
{
down = false;
up = false;
right = false;
left = true;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (down) { snake.moveDown(); }
if (up) { snake.moveUp(); }
if (right) { snake.moveRight(); }
if (left) { snake.moveLeft(); }
this.Invalidate();
}
}
}
Here is my Snake class if you need it.
{
public Snake()
{
snakeRec = new Rectangle[3];
brush = new SolidBrush(Color.Blue);
x = 20;
y = 0;
width = 10;
height = 10;
for(int i = 0; i < snakeRec.Length; i++)
{
snakeRec[i] = new Rectangle(x, y, width, height);
x -= 10;
}
}
public void drawSnake(Graphics paper)
{
foreach (Rectangle rec in snakeRec)
{
paper.FillRectangle(brush, rec);
}
}
public void drawSnake()
{
for (int i = snakeRec.Length - 1; i > 0; i--)
{
snakeRec[i] = snakeRec[i - 1];
}
}
public void moveDown()
{
drawSnake();
snakeRec[0].Y += 10;
}
public void moveUp()
{
drawSnake();
snakeRec[0].Y -= 10;
}
public void moveRight()
{
drawSnake();
snakeRec[0].X += 10;
}
public void moveLeft()
{
drawSnake();
snakeRec[0].X -= 10;
}
}
}
I tried your code and it works well, so this is the only thing I can think of:
private void Form1_Load(object sender, EventArgs e)
{
timer1.Enabled = true;
}
Make sure that big guy is enabled.
Don't hold on to the Graphics from the Paint() event like that. Just pass e.Graphics directly to your Draw() method like this:
private void Form1_Paint(object sender, PaintEventArgs e)
{
snake.drawSnake(e.Graphics);
}
Also, make sure the Paint() event of the Form is wired up. Select the Form. Now click the "Lightning" Bolt" icon in the Properties Pane (bottom right by default). Find the Paint entry and change the dropdown to the right to "Form1_Paint".

C# drag controls around a panel

i am developing a system which allow user to drag objects around within a same panel, i went through some research and founds that i should use mouse events like mouse_up, mouse_down and mouse_move.
The the program will generate 3 picturebox and allow the user to drag around the every picturebox within the panel, but the program i code did not work perfectly as when i drag over a picturebox, the picturebox will move, but not according to my mouse cursor location, it is somewhere else, besides, when dragging, there is picturebox shadows in the panel, i've tried those update(),refresh(), and invalidate() but it seems not useful for me. Below are my codes, thanks for helping
public partial class Form1 : Form
{
List<PictureBox> pictureBoxList = new List<PictureBox>();
private bool isDragging = false;
public Form1()
{
InitializeComponent();
for (int i = 0; i < 3; i++)
{
PictureBox picture = new PictureBox
{
Name = "pictureBox" + i,
Size = new Size(20, 20),
Location = new Point(i * 40, i * 40),
BorderStyle = BorderStyle.FixedSingle,
SizeMode = PictureBoxSizeMode.Zoom,
ImageLocation = "A.jpg"
};
pictureBoxList.Add(picture);
foreach (PictureBox p in pictureBoxList)
{
p.MouseDown += new MouseEventHandler(c_MouseDown);
p.MouseMove += new MouseEventHandler(c_MouseMove);
p.MouseUp += new MouseEventHandler(c_MouseUp);
pnlDisplayImage.Controls.Add(p);
pnlDisplayImage.Refresh();
}
}
}
void c_MouseDown(object sender, MouseEventArgs e)
{
isDragging = true;
}
void c_MouseMove(object sender, MouseEventArgs e)
{
if (isDragging == true) {
Control c = sender as Control;
for (int i = 0; i < pictureBoxList.Count(); i++)
{
if (c.Equals(pictureBoxList[i]))
{
pictureBoxList[i].Location = new Point(e.X, e.Y);
}
}
}
}
void c_MouseUp(object sender, MouseEventArgs e)
{
PictureBox c = sender as PictureBox;
isDragging = false;
for (int i = 0; i < pictureBoxList.Count(); i++) {
if (c.Equals(pictureBoxList[i])){
pictureBoxList[i].Location = new Point(e.X, e.Y);
}
}
}
private void pnlDisplayImage_Paint(object sender, PaintEventArgs e)
{
foreach (PictureBox p in pictureBoxList)
{
pnlDisplayImage.Controls.Add(p);
}
}
}
Finally I've found what are the problems that caused my program not running as my expectations. The main problem is that I accidentally put the foreach loop inside the for loop which I used to create pictureBox, this problem caused the pictureBox comes out some shadows effect while dragging during run time due to there are few same pictureBox. Also, I have change a little bit of the codes and it now run as what I expected. Below are the code that I want for answer.
public partial class Form1 : Form
{
List<PictureBox> pictureBoxList = new List<PictureBox>();
private bool isDragging = false;
Point move;
public Form1()
{
InitializeComponent();
for (int i = 0; i < 3; i++)
{
PictureBox picture = new PictureBox
{
Name = "pictureBox" + i,
Size = new Size(20, 20),
Location = new Point(i * 40, i * 40),
BorderStyle = BorderStyle.FixedSingle,
SizeMode = PictureBoxSizeMode.Zoom,
ImageLocation = "A.jpg"
};
pictureBoxList.Add(picture);
}
foreach (PictureBox p in pictureBoxList)
{
p.MouseDown += new MouseEventHandler(c_MouseDown);
p.MouseMove += new MouseEventHandler(c_MouseMove);
p.MouseUp += new MouseEventHandler(c_MouseUp);
pnlDisplayImage.Controls.Add(p);
pnlDisplayImage.Refresh();
}
}
void c_MouseDown(object sender, MouseEventArgs e)
{
Control c = sender as Control;
isDragging = true;
move = e.Location;
}
void c_MouseMove(object sender, MouseEventArgs e)
{
if (isDragging == true) {
Control c = sender as Control;
for (int i = 0; i < pictureBoxList.Count(); i++)
{
if (c.Equals(pictureBoxList[i]))
{
pictureBoxList[i].Left += e.X - move.X;
pictureBoxList[i].Top += e.Y - move.Y;
}
}
}
}
void c_MouseUp(object sender, MouseEventArgs e)
{
isDragging = false;
}
}
Try something like (it's custom control with overrides, but should be easy to convert to events):
private bool _isMoved = false; // true if move mode on
private Point _pointMove = new Point(0); // for moving
protected override void OnMouseDown(MouseEventArgs e)
{
// if left button pressed
if(e.Button == MouseButtons.Left)
{
_pointMove.X = e.X;
_pointMove.Y = e.Y;
_isMoved = true;
Cursor = Cursors.SizeAll;
Capture = true;
}
base.OnMouseDown (e);
}
protected override void OnMouseUp(MouseEventArgs e)
{
// if move mode on
if(_isMoved)
{
_isMoved = false;
Cursor = Cursors.Default;
Capture = false;
}
base.OnMouseUp (e);
}
protected override void OnMouseMove(MouseEventArgs e)
{
// if move mode on
if (_isMoved)
{
Left += e.X - _pointMove.X;
Top += e.Y - _pointMove.Y;
}
base.OnMouseMove (e);
}

Categories

Resources