图形类:如何在图像的顶部,左侧,右侧和底部创建边距

时间:2013-09-02 11:20:00

标签: c#

在Image Magick上,我们可以使用-splice选项和-gravity选项在图像的顶部,左侧,右侧和底部创建边距。

我想使用C#Graphics类在图像的顶部,左侧,右侧和底部创建边距。

但我不知道如何使用C#类创建边距,可以使用C#类创建边距。

所以,我想知道上面提到的。

2 个答案:

答案 0 :(得分:3)

您不希望在C#图形类上创建边距。

Graphics对象是“能够被吸引的东西”的抽象。它可以是屏幕,打印机或位图。

您无法调整位图的大小。您必须创建一个新的,并将现有的一个复制到其上。

所以你需要做的是创建一个新的位图,它是现有位图的副本,但是有一个边距,然后使用Graphics对象将位图复制到它上面。

所以你需要

  • 创建一个足够大的位图,以获得位图和边距。使用“宽度”和“高度”属性查找现有位图的大小。
  • 创建一个Graphics对象,允许您在位图上绘制(检查构造函数重载)
  • 然后使用图形对象将旧位图复制到新位图中。 (查看DrawImage方法)
  • 最后处理图形对象,并以所需格式保存位图。

答案 1 :(得分:1)

通常,您正在定义System.Windows.Forms.Control / Form实例本身的边距。查看VisualStudio的设计者。并且 - 如果您需要在OnPaint方法或Paint事件中自己绘制控件,则可以尝试以下操作之一。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        static readonly Bitmap image = Properties.Resources.gecco_quad_dunkel;

        public Form1()
        {
            InitializeComponent();
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {
            // using my own margin
            const int margin = 20;

            var dest = new Rectangle(
                e.ClipRectangle.X + margin, 
                e.ClipRectangle.Y + margin, 
                e.ClipRectangle.Width - 2 * margin, 
                e.ClipRectangle.Height - 2 * margin
                );

            e.Graphics.DrawImage(image, dest);
        }

        private void panel2_Paint(object sender, PaintEventArgs e)
        {
            // using the margin information of the System.Windows.Forms.Control/Form

            var co = (Control)sender;
            var dest = new Rectangle(
                e.ClipRectangle.X + co.Margin.Left, 
                e.ClipRectangle.Y + co.Margin.Top, 
                e.ClipRectangle.Width - co.Margin.Left - co.Margin.Right, 
                e.ClipRectangle.Height - co.Margin.Top - co.Margin.Bottom
                );

            e.Graphics.DrawImage(image, dest);
        }
    }
}

在我的表格中,我添加了两个绿色和橙色的容器(面板)。橙色的边缘各边都有20px的边距。 enter image description here