0

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

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

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

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

4

2 回答 2

4

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

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

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

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

所以你需要

  • 创建一个足够大的位图以包含位图和边距。使用 Width 和 Height 属性找出现有位图的大小。
  • 创建一个允许您在位图上绘制的 Graphics 对象(检查构造函数重载)
  • 然后使用图形对象将旧位图复制到新位图中。(查看 DrawImage 方法)
  • 最后处理图形对象,并将位图保存为所需的格式。
于 2013-09-02T11:29:01.293 回答
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 的边距。 在此处输入图像描述

于 2013-09-02T13:11:10.640 回答