从缩放的单位位图中删除颜色渐变

时间:2014-06-10 13:56:17

标签: c# image winforms bitmap

我正在尝试按xs红色ys创建Bitmap并遇到问题。

我这样做的功能如下:(参考:https://stackoverflow.com/a/12502878/1596244

private Bitmap getBlankBitmap(int xs, int ys)
{
    Bitmap b = new Bitmap(1, 1);
    b.SetPixel(0, 0, Color.Red);
    return new Bitmap(b, xs, ys);
}

虽然问题是,这会在Bitmap上创建一个颜色渐变,我只希望每个像素都是指定的颜色。如何删除此渐变和"完全"为Bitmap着色?

以下是我使用http://msdn.microsoft.com/en-us/library/334ey5b7.aspx的构造函数,它根本没有提到添加渐变,我甚至不确定为什么这将是默认行为。

enter image description here

这是一个与

一起使用的SSCCE
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 TestProject2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            showIssue();
        }

        void showIssue()
        {
            pictureBox1.Image = getBlankBitmap(pictureBox1.Size.Width, pictureBox1.Size.Height);
        }

        private Bitmap getBlankBitmap(int xs, int ys)
        {
            Bitmap b = new Bitmap(1, 1);
            b.SetPixel(0, 0, Color.Red);
            return new Bitmap(b, xs, ys);
        }

        private System.ComponentModel.IContainer components = null;

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void InitializeComponent()
        {
            this.pictureBox1 = new System.Windows.Forms.PictureBox();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
            this.SuspendLayout();
            // 
            // pictureBox1
            // 
            this.pictureBox1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.pictureBox1.Location = new System.Drawing.Point(0, 0);
            this.pictureBox1.Name = "pictureBox1";
            this.pictureBox1.Size = new System.Drawing.Size(477, 344);
            this.pictureBox1.TabIndex = 0;
            this.pictureBox1.TabStop = false;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(477, 344);
            this.Controls.Add(this.pictureBox1);
            this.Name = "Form1";
            this.Text = "Form1";
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
            this.ResumeLayout(false);

        }

        private System.Windows.Forms.PictureBox pictureBox1;
    }
}

1 个答案:

答案 0 :(得分:1)

只需创建一个具有所需尺寸的新位图并将其涂成红色:

private Bitmap getBlankBitmap(int width, int height) {
  Bitmap b = new Bitmap(width, height);
  using (Graphics g = Graphics.FromImage(b)) {
    g.Clear(Color.Red);
  }
  return b;
}