代码之家  ›  专栏  ›  技术社区  ›  Sindre Sorhus

淡入/淡出图像的最佳方式

  •  1
  • Sindre Sorhus  · 技术社区  · 16 年前

    在C#中,在黑色背景(屏幕保护程序)下,每20秒淡入淡出一幅图像(持续时间为1秒)的最佳方式(资源最少)是什么?

    (图像约350x130px)。

    现在我正在对pictureBox使用此方法,但速度太慢:

        private Image Lighter(Image imgLight, int level, int nRed, int nGreen, int nBlue)
        {
            Graphics graphics = Graphics.FromImage(imgLight);
            int conversion = (5 * (level - 50));
            Pen pLight = new Pen(Color.FromArgb(conversion, nRed,
                                 nGreen, nBlue), imgLight.Width * 2);
            graphics.DrawLine(pLight, -1, -1, imgLight.Width, imgLight.Height);
            graphics.Save();
            graphics.Dispose();
            return imgLight;
        }
    
    4 回复  |  直到 16 年前
        2
  •  1
  •   Andrew Morton    5 年前

    您可以使用 Bitmap.LockBits 直接访问图像的内存。这里有一个 good explanation 它是如何工作的。

        3
  •  0
  •   Charles Bretana    16 年前

        timr.Interval = //whatever interval you want it to fire at;
        timr.Tick += FadeInAndOut;
        timr.Start();
    

    添加一个私有方法

    private void FadeInAndOut(object sender, EventArgs e)
    {
        Opacity -= .01; 
        timr.Enabled = true;
        if (Opacity < .05) Opacity = 1.00;
    }
    
        4
  •  0
  •   vbtheory    13 年前

    这是我对这件事的看法

        private void animateImageOpacity(PictureBox control)
        {
            for(float i = 0F; i< 1F; i+=.10F)
            {
                control.Image = ChangeOpacity(itemIcon[selected], i);
                Thread.Sleep(40);
            }
        }
    
        public static Bitmap ChangeOpacity(Image img, float opacityvalue)
        {
            Bitmap bmp = new Bitmap(img.Width, img.Height); // Determining Width and Height of Source Image
            Graphics graphics = Graphics.FromImage(bmp);
            ColorMatrix colormatrix = new ColorMatrix {Matrix33 = opacityvalue};
            ImageAttributes imgAttribute = new ImageAttributes();
            imgAttribute.SetColorMatrix(colormatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
            graphics.DrawImage(img, new Rectangle(0, 0, bmp.Width, bmp.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel, imgAttribute);
            graphics.Dispose();   // Releasing all resource used by graphics 
            return bmp;
        }
    

    还建议创建另一个线程,因为这将冻结主线程。

    推荐文章