Winform 通过计时器实现图片缩放功能

本文最后更新于:1 年前

Winform 通过计时器实现图片缩放功能

写在前面

hello,好久不见噢,距离上一次更新又过了一个月,这段时间在忙很多事。主要谈一谈技术上吧,机器学习的老师帮忙联系了一个C#的实习,犹豫了一下就果断发简历了,虽然之前从未接触过C#,但正巧自己需要丰富实习经历,再加上不需要线下,就当换换脑子了。这几天一直在狂补Winform的基础语法,从一开始的拿到程序都不会用到现在可以自己写一写简单的窗口程序了,感觉很不错。

这个项目其中的一个比较重要的功能就是在窗口的左侧绘制一张原图片,通过鼠标在上面移动,能在右侧绘制出鼠标周围图片的缩放。老师说利用多线程也可以,奈何自己才疏学浅,感觉计时器完成刷新率(每秒60帧)也可以接受,就果断采用了。

正文

先创建两个picturebox,把原图片也放上去。利用截屏方法提取图像,显示在右侧picturebox。再利用计时器实现不断刷新就行了。

上代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;

namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
int magnification = 1; //倍率,调节放大倍数,可由TrackBar控制调节
int mx; //鼠标x坐标
int my; //鼠标y坐标
const int imgWidth = 400; //放大后图片的宽度
const int imgHeight = 400; //放大后图片的高度

public Form1()
{
InitializeComponent();

// 将原图像显示在pictureBox1
Image img = Image.FromFile("Earth.bmp");// 建立Image对象
pictureBox1.Image = img;
}

// 计时器
private void timer1_Tick(object sender, EventArgs e)
{
mx = pictureBox1.PointToClient(Control.MousePosition).X;
my = pictureBox1.PointToClient(Control.MousePosition).Y;

// 检测鼠标是否在pictureBox1中
// 若是,pictureBox2显示其缩放
bool b = pictureBox1.RectangleToScreen(pictureBox1.ClientRectangle).Contains(MousePosition);
if (!b)
{
pictureBox2.Image = null;
}
else
{
//对图像进行放大显示 
Bitmap bt = new Bitmap(imgWidth / magnification, imgHeight / magnification);
Graphics g = Graphics.FromImage(bt);
g.CopyFromScreen(
new Point(Cursor.Position.X - imgWidth / (2 * magnification),
Cursor.Position.Y - imgHeight / (2 * magnification)),
//new Point(mx - (imgWidth / (2 * magnification)),
// my - (imgHeight / (2 * magnification))),
new Point(0, 0),
new Size(imgWidth / magnification, imgHeight / magnification));
IntPtr dc1 = g.GetHdc();
g.ReleaseHdc(dc1);
pictureBox2.Image = (Image)bt;
}
}


private void trackBar1_Scroll(object sender, EventArgs e)
{
label1.Text = "x" + trackBar1.Value.ToString();
}

private void trackBar1_ValueChanged(object sender, EventArgs e)
{
magnification = trackBar1.Value;
}

}
}

效果图:

图为运行效果

写在后面

最近总是看到一些看低cpp就业的文章,弄得自己很焦虑,加上身边学前端的朋友们也都陆续找到了实习,自己却没有勇气前进,负面情绪高涨。不过在身边朋友鼓励下,还是毅然决然坚持cpp的道路,希望最后的结局配得上我为之付出的努力。这个c#系列我有什么想法也依然会更新的。