绘制位图 C# [英] Draw a bitmap C#
问题描述
我正在尝试使用位图类在屏幕上绘制图像,但出了点问题.
I am trying to draw an image on the screen with bitmap class but something is wrong.
这是我的代码:
Bitmap bm = new Bitmap(@"C:\Alan\University\111.jpg");
Graphics g = Graphics.FromImage(bm);
g.DrawImage(bm,60,60);
运行代码后,我的屏幕上没有任何附加内容.我的代码有什么问题?谢谢
after running the code nothing append on my screen. what is wrong in my code? thanks
推荐答案
您正在从 Image
本身创建图形对象,然后尝试将图像绘制到其自身上.您需要将图像绘制到另一个 Graphics
对象中.通常代表屏幕或您希望显示图像的组件.
You're making a graphics object from the Image
itself and then you try to draw the image onto itself. You need to draw the image into another Graphics
object. Typically something representing the screen or the component where you want the image displayed.
您没有指定尝试在哪种上下文中绘制图像.如何获取 Graphics
对象取决于框架(WPF、WinForms 等).对于典型的 winforms 应用程序,您希望像这样覆盖窗口中的 OnPaint
:
You don't specify in what sort of context you try to draw the image in. How to get the Graphics
object depends on the framework (WPF, WinForms etc). For a typical winforms application you want to override OnPaint
in your window like this:
protected override void OnPaint(PaintEventArgs e)
{
Bitmap bm = new Bitmap(@"C:\Alan\University\111.jpg");
// Draw using this
e.Graphics.DrawImage(bm,60,60);
base.OnPaint(e);
}
当然,您希望在某些启动方法中只加载一次图像,而不是每次绘制表单时都加载.
Of course, you would want to load the image only once at some startup method and not every time you draw the form.
这篇关于绘制位图 C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!