検索
ホームページバックエンド開発C#.Net チュートリアルC# で QQ スタイルのスクリーンショット機能を実装するサンプル コードの詳細な紹介

この記事では、QQ スタイルのスクリーンショット機能を実装するための C# のサンプル コードを主に紹介します。編集者がそれを参考として共有します。エディターに従って見てみましょう。この関数は 2 つの部分で構成されています。最初の部分はフォーム コードであり、もう 1 つの部分は補助メソッドです。参考のためにコードを直接投稿してください:


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;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using ImageClassLib;
namespace ImageShear
{
  public partial class Demo: Form
  {
    public Demo()
    {
      InitializeComponent();
    }
    #region 点击打开图像
    public string strHeadImagePath; //打开图片的路径
    Bitmap Bi; //定义位图对像
    private void button1_Click(object sender, EventArgs e)
    {
      openFileDialog1.Filter = "*.gif|*.jpg|*.JPEG|*.JPEG|*.bmp|*.bmp";     //设置读取图片类型
      if (openFileDialog1.ShowDialog() == DialogResult.OK)
      {
        try
        {
          strHeadImagePath = openFileDialog1.FileName;
          //this.Show(strHeadImagePath);
          Bi = new Bitmap(strHeadImagePath); //使用打开的图片路径创建位图对像
          ImageCut1 IC = new ImageCut1(40, 112, this.pictureBox1.Width, this.pictureBox1.Height);   //实例化ImageCut类,四个参数据分别表示为:x、y、width、heigth,(40、112)表示pictureBox1的Lcation的坐标,(120、144)表示pictureBox1控件的宽度和高度
          this.pictureBox1.Image = IC.KiCut1((Bitmap)(this.GetSelectImage(this.pictureBox1.Width, this.pictureBox1.Height)));   //(120、144)表示pictureBox1控件的宽度和高度
          //this.pictureBox1.Image = (this.GetSelectImage(120, 144));
        }
        catch (Exception ex)
        {
          MessageBox.Show("格式不对");
          ex.ToString();
        }
      }
    }
    #endregion
    #region 定义显示图像方法,即将打开的图像在pictureBox1控件显示
    public void Show(string strHeadImagePath)
    {
      this.pictureBox1.Load(@strHeadImagePath);  //
    }
    #endregion
    #region 获取图像
    /// <summary>
    /// 获取指定宽度和高度的图像即使图片和pictureBox1控件一样宽和高,返回值为图片Image
    /// </summary>
    /// <param name="Width表示宽"></param>
    /// <param name="Height表示高"></param>
    /// <returns></returns>
    public Image GetSelectImage(int Width, int Height)
    {
      //Image initImage = this.pictureBox1.Image;
      Image initImage = Bi;
      //原图宽高均小于模版,不作处理,直接保存 
      if (initImage.Width <= Width && initImage.Height <= Height)
      {
        //initImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);
        return initImage;
      }
      else
      {
        //原始图片的宽、高 
        int initWidth = initImage.Width;
        int initHeight = initImage.Height;

        //非正方型先裁剪为正方型 
        if (initWidth != initHeight)
        {
          //截图对象 
          System.Drawing.Image pickedImage = null;
          System.Drawing.Graphics pickedG = null;

          //宽大于高的横图 
          if (initWidth > initHeight)
          {
            //对象实例化 
            pickedImage = new System.Drawing.Bitmap(initHeight, initHeight);
            pickedG = System.Drawing.Graphics.FromImage(pickedImage);
            //设置质量 
            pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            pickedG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //定位 
            Rectangle fromR = new Rectangle((initWidth - initHeight) / 2, 0, initHeight, initHeight);
            Rectangle toR = new Rectangle(0, 0, initHeight, initHeight);
            //画图 
            pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel);
            //重置宽 
            initWidth = initHeight;
          }
          //高大于宽的竖图 
          else
          {
            //对象实例化
            pickedImage = new System.Drawing.Bitmap(initWidth, initWidth);
            pickedG = System.Drawing.Graphics.FromImage(pickedImage);
            //设置质量 
            pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            pickedG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //定位 
            Rectangle fromR = new Rectangle(0, (initHeight - initWidth) / 2, initWidth, initWidth);
            Rectangle toR = new Rectangle(0, 0, initWidth, initWidth);
            //画图 
            pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel);
            //重置高 
            initHeight = initWidth;
          }

          initImage = (System.Drawing.Image)pickedImage.Clone();
          //        //释放截图资源 
          pickedG.Dispose();
          pickedImage.Dispose();
        }

        return initImage;
      }
    }
    #endregion
    #region 点击button2按钮事件
    private void button2_Click(object sender, EventArgs e)
    {
      this.label1.Text = "裁剪后的图片宽度:"+this.pictureBox2.Width.ToString();
      this.label2.Text = "裁剪后的图片高度:"+this.pictureBox2.Height.ToString();
    }
    #endregion
    #region 缩放、裁剪图像用到的变量
    /// <summary>
    /// 
    /// </summary>
    int x1;   //鼠标按下时横坐标
    int y1;   //鼠标按下时纵坐标
    int width; //所打开的图像的宽
    int heigth; //所打开的图像的高
    bool HeadImageBool = false;  // 此布尔变量用来判断pictureBox1控件是否有图片
    #endregion
    #region 画矩形使用到的变量
    Point p1;  //定义鼠标按下时的坐标点
    Point p2;  //定义移动鼠标时的坐标点
    Point p3;  //定义松开鼠标时的坐标点
    #endregion
    #region 鼠标按下时发生的事件
    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
      this.Cursor = Cursors.Cross;
      this.p1 = new Point(e.X, e.Y);
      x1 = e.X;
      y1 = e.Y;
      if (this.pictureBox1.Image != null)
      {
        HeadImageBool = true;
      }
      else
      {
        HeadImageBool = false;
      }
    }
    #endregion
    #region 移动鼠标发生的事件
    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
      if (this.Cursor == Cursors.Cross)
      {
        this.p2 = new Point(e.X, e.Y);
        if ((p2.X - p1.X) > 0 && (p2.Y - p1.Y) > 0)   //当鼠标从左上角向开始移动时P3坐标
        {
          this.p3 = new Point(p1.X, p1.Y);
        }
        if ((p2.X - p1.X) < 0 && (p2.Y - p1.Y) > 0)   //当鼠标从右上角向左下方向开始移动时P3坐标
        {
          this.p3 = new Point(p2.X, p1.Y);
        }
        if ((p2.X - p1.X) > 0 && (p2.Y - p1.Y) < 0)   //当鼠标从左下角向上开始移动时P3坐标
        {
          this.p3 = new Point(p1.X, p2.Y);
        }
        if ((p2.X - p1.X) < 0 && (p2.Y - p1.Y) < 0)   //当鼠标从右下角向左方向上开始移动时P3坐标
        {
          this.p3 = new Point(p2.X, p2.Y);
        }
        this.pictureBox1.Invalidate(); //使控件的整个图面无效,并导致重绘控件
      }
    }
    #endregion
    #region 松开鼠标发生的事件,实例化ImageCut1类对像
    ImageCut1 IC1; //定义所画矩形的图像对像
    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
      if (HeadImageBool)
      {
        width = this.pictureBox1.Image.Width;
        heigth = this.pictureBox1.Image.Height;
        if ((e.X - x1) > 0 && (e.Y - y1) > 0)  //当鼠标从左上角向右下方向开始移动时发生
        {
          IC1 = new ImageCut1(x1, y1, Math.Abs(e.X - x1), Math.Abs(e.Y - y1));  //实例化ImageCut1类
        }
        if ((e.X - x1) < 0 && (e.Y - y1) > 0)  //当鼠标从右上角向左下方向开始移动时发生
        {
          IC1 = new ImageCut1(e.X, y1, Math.Abs(e.X - x1), Math.Abs(e.Y - y1));  //实例化ImageCut1类
        }
        if ((e.X - x1) > 0 && (e.Y - y1) < 0)  //当鼠标从左下角向右上方向开始移动时发生
        {
          IC1 = new ImageCut1(x1, e.Y, Math.Abs(e.X - x1), Math.Abs(e.Y - y1));  //实例化ImageCut1类
        }
        if ((e.X - x1) < 0 && (e.Y - y1) < 0)  //当鼠标从右下角向左上方向开始移动时发生
        {
          IC1 = new ImageCut1(e.X, e.Y, Math.Abs(e.X - x1), Math.Abs(e.Y - y1));   //实例化ImageCut1类
        }
        this.pictureBox2.Width = (IC1.KiCut1((Bitmap)(this.pictureBox1.Image))).Width;
        this.pictureBox2.Height = (IC1.KiCut1((Bitmap)(this.pictureBox1.Image))).Height;
        this.pictureBox2.Image = IC1.KiCut1((Bitmap)(this.pictureBox1.Image));
        this.Cursor = Cursors.Default;
      }
      else
      {
        this.Cursor = Cursors.Default;
      }
    }
    #endregion
    #region 获取所选矩形图像
    /// <summary>
    /// 
    /// </summary>
    /// <param name="Width"></param>
    /// <param name="Height"></param>
    /// <returns></returns>
    public Image GetSelectImage1(int Width, int Height)
    {
      Image initImage = this.pictureBox1.Image;
      //Image initImage = Bi;
      //原图宽高均小于模版,不作处理,直接保存 
      if (initImage.Width <= Width && initImage.Height <= Height)
      {
        //initImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);
        return initImage;
      }
      else
      {
        //原始图片的宽、高 
        int initWidth = initImage.Width;
        int initHeight = initImage.Height;

        //非正方型先裁剪为正方型 
        if (initWidth != initHeight)
        {
          //截图对象 
          System.Drawing.Image pickedImage = null;
          System.Drawing.Graphics pickedG = null;

          //宽大于高的横图 
          if (initWidth > initHeight)
          {
            //对象实例化 
            pickedImage = new System.Drawing.Bitmap(initHeight, initHeight);
            pickedG = System.Drawing.Graphics.FromImage(pickedImage);
            //设置质量 
            pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            pickedG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //定位 
            Rectangle fromR = new Rectangle((initWidth - initHeight) / 2, 0, initHeight, initHeight);
            Rectangle toR = new Rectangle(0, 0, initHeight, initHeight);
            //画图 
            pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel);
            //重置宽 
            initWidth = initHeight;
          }
          //高大于宽的竖图 
          else
          {
            //对象实例化
            pickedImage = new System.Drawing.Bitmap(initWidth, initWidth);
            pickedG = System.Drawing.Graphics.FromImage(pickedImage);
            //设置质量 
            pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            pickedG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //定位 
            Rectangle fromR = new Rectangle(0, (initHeight - initWidth) / 2, initWidth, initWidth);
            Rectangle toR = new Rectangle(0, 0, initWidth, initWidth);
            //画图 
            pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel);
            //重置高 
            initHeight = initWidth;
          }

          initImage = (System.Drawing.Image)pickedImage.Clone();
          //        //释放截图资源 
          pickedG.Dispose();
          pickedImage.Dispose();
        }

        return initImage;
      }
    }
    #endregion
    #region 重新绘制pictureBox1控件,即移动鼠标画矩形
    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
      if (HeadImageBool)
      {
        Pen p = new Pen(Color.Black, 1);//画笔
        p.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
        //Bitmap bitmap = new Bitmap(strHeadImagePath);
        Bitmap bitmap = Bi;
        Rectangle rect = new Rectangle(p3, new Size(System.Math.Abs(p2.X - p1.X), System.Math.Abs(p2.Y - p1.Y)));
        e.Graphics.DrawRectangle(p, rect);
      }
      else
      {

      }
    }
    #endregion
  }
}

2 番目の部分は補助メソッド クラスです


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
namespace ImageClassLib
{
  public class ImageCut1
  {
    #region 剪裁图片方法
    /// <summary> 
    /// 剪裁 -- 用GDI+ 
    /// </summary> 
    /// <param name="b">原始Bitmap,即需要裁剪的图片</param> 
    /// <param name="StartX">开始坐标X</param> 
    /// <param name="StartY">开始坐标Y</param> 
    /// <param name="iWidth">宽度</param> 
    /// <param name="iHeight">高度</param> 
    /// <returns>剪裁后的Bitmap</returns> 
    public Bitmap KiCut1(Bitmap b) 
    { 
      if (b == null) 
      { 
        return null; 
      } 
    
      int w = b.Width; 
      int h = b.Height; 
    
      if (X >= w || Y >= h) 
      { 
        return null; 
      } 
    
      if (X + Width > w) 
      { 
        Width = w - X; 
      } 
    
      if (Y + Height > h) 
      { 
        Height = h - Y; 
      } 
    
      try
      { 
        Bitmap bmpOut = new Bitmap(Width, Height, PixelFormat.Format24bppRgb); 
    
        Graphics g = Graphics.FromImage(bmpOut);
        // Create rectangle for displaying image.
        Rectangle destRect = new Rectangle(0, 0, Width, Height);    //所画的矩形正确,它指定所绘制图像的位置和大小。 将图像进行缩放以适合该矩形。

        // Create rectangle for source image.
        Rectangle srcRect = new Rectangle(X, Y, Width, Height);   //srcRect参数指定要绘制的 image 对象的矩形部分。 将此部分进行缩放以适合 destRect 参数所指定的矩形。

        g.DrawImage(b, destRect, srcRect, GraphicsUnit.Pixel);
        //resultG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, side, side), new System.Drawing.Rectangle(0, 0, initWidth, initHeight), System.Drawing.GraphicsUnit.Pixel);
        g.Dispose(); 
        return bmpOut; 
      } 
      catch
      { 
        return null; 
      } 
    }
    #endregion
    #region ImageCut1类的构造函数
    public int X; 
    public int Y; 
    public int Width ; 
    public int Height;
    /// <summary>
    /// ImageCut1类的构造函数,ImageCut1类用来获取鼠标在pictureBox1控件所画矩形内的图像
    /// </summary>
    /// <param name="x表示鼠标在pictureBox1控件上按下时的横坐标"></param>
    /// <param name="y表示鼠标在pictureBox1控件上按下时的纵坐标"></param>
    /// <param name="width表示鼠标在pictureBox1控件上松开鼠标的宽度"></param>
    /// <param name="heigth表示鼠标在pictureBox1控件上松开鼠标的高度"></param>
    public ImageCut1(int x, int y, int width, int heigth)
    {
      X = x;
      Y = y;
      Width = width;
      Height = heigth;
    }
    #endregion
  }
}

達成される効果は次のとおりです:

上記はのスクリーンショットです。 QQ スタイルの C# 実装 関数のサンプル コードが詳しく紹介されています。関連コンテンツについては、PHP 中国語 Web サイト (www.php.cn) を参照してください。


声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
C#と.NET:2つの関係を理解し​​ますC#と.NET:2つの関係を理解し​​ますApr 17, 2025 am 12:07 AM

C#と.NETの関係は切り離せませんが、同じものではありません。 C#はプログラミング言語であり、.NETは開発プ​​ラットフォームです。 C#は、コードの書き込み、.NETの中間言語(IL)にコンパイルされ、.NET Runtime(CLR)によって実行されるために使用されます。

c#.netの継続的な関連性:現在の使用法を見るc#.netの継続的な関連性:現在の使用法を見るApr 16, 2025 am 12:07 AM

C#.NETは、複数のアプリケーション開発をサポートする強力なツールとライブラリを提供するため、依然として重要です。 1)C#は.NETフレームワークを組み合わせて、開発を効率的かつ便利にします。 2)C#のタイプの安全性とゴミ収集メカニズムは、その利点を高めます。 3).NETは、クロスプラットフォームの実行環境とリッチAPIを提供し、開発の柔軟性を向上させます。

Webからデスクトップまで:C#.NETの汎用性Webからデスクトップまで:C#.NETの汎用性Apr 15, 2025 am 12:07 AM

c#.netisversatileforbothwebanddesktopdevelopment.1)forweb、useasp.netfordynamicapplications.2)fordesktop、equindowsorwpfforrichinterfaces.3)usexamarinforcross-platformdeveliment、enabling deshacrosswindows、

c#.net and the Future:新しいテクノロジーへの適応c#.net and the Future:新しいテクノロジーへの適応Apr 14, 2025 am 12:06 AM

C#と.NETは、継続的な更新と最適化を通じて、新しいテクノロジーのニーズに適応します。 1)C#9.0および.NET5は、レコードタイプとパフォーマンスの最適化を導入します。 2).Netcoreは、クラウドネイティブおよびコンテナ化されたサポートを強化します。 3)ASP.Netcoreは、最新のWebテクノロジーと統合されています。 4)ML.NETは、機械学習と人工知能をサポートしています。 5)非同期プログラミングとベストプラクティスはパフォーマンスを改善します。

c#.netはあなたにぴったりですか?その適用性の評価c#.netはあなたにぴったりですか?その適用性の評価Apr 13, 2025 am 12:03 AM

c#.netissuitableforenterprise-levelApplicationsとsystemduetoitsSystemdutyping、richlibraries、androbustperformance.

.NET内のC#コード:プログラミングプロセスの調査.NET内のC#コード:プログラミングプロセスの調査Apr 12, 2025 am 12:02 AM

.NETでのC#のプログラミングプロセスには、次の手順が含まれます。1)C#コードの作成、2)中間言語(IL)にコンパイルし、3).NETランタイム(CLR)によって実行される。 .NETのC#の利点は、デスクトップアプリケーションからWebサービスまでのさまざまな開発シナリオに適した、最新の構文、強力なタイプシステム、および.NETフレームワークとの緊密な統合です。

C#.NET:コアの概念とプログラミングの基礎を探るC#.NET:コアの概念とプログラミングの基礎を探るApr 10, 2025 am 09:32 AM

C#は、Microsoftによって開発された最新のオブジェクト指向プログラミング言語であり、.NETフレームワークの一部として開発されています。 1.C#は、カプセル化、継承、多型を含むオブジェクト指向プログラミング(OOP)をサポートしています。 2。C#の非同期プログラミングは非同期を通じて実装され、適用応答性を向上させるためにキーワードを待ちます。 3. LINQを使用してデータ収集を簡潔に処理します。 4.一般的なエラーには、null参照の例外と、範囲外の例外インデックスが含まれます。デバッグスキルには、デバッガーと例外処理の使用が含まれます。 5.パフォーマンスの最適化には、StringBuilderの使用と、不必要な梱包とボクシングの回避が含まれます。

テストC#.NETアプリケーション:ユニット、統合、およびエンドツーエンドテストテストC#.NETアプリケーション:ユニット、統合、およびエンドツーエンドテストApr 09, 2025 am 12:04 AM

C#.NETアプリケーションのテスト戦略には、ユニットテスト、統合テスト、エンドツーエンドテストが含まれます。 1.単位テストにより、コードの最小ユニットがMSTEST、ヌニット、またはXUNITフレームワークを使用して独立して動作することを保証します。 2。統合テストでは、一般的に使用されるシミュレートされたデータと外部サービスを組み合わせた複数のユニットの機能を検証します。 3.エンドツーエンドのテストでは、ユーザーの完全な操作プロセスをシミュレートし、通常、セレンは自動テストに使用されます。

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

AtomエディタMac版ダウンロード

AtomエディタMac版ダウンロード

最も人気のあるオープンソースエディター

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。

SecLists

SecLists

SecLists は、セキュリティ テスターの究極の相棒です。これは、セキュリティ評価中に頻繁に使用されるさまざまな種類のリストを 1 か所にまとめたものです。 SecLists は、セキュリティ テスターが必要とする可能性のあるすべてのリストを便利に提供することで、セキュリティ テストをより効率的かつ生産的にするのに役立ちます。リストの種類には、ユーザー名、パスワード、URL、ファジング ペイロード、機密データ パターン、Web シェルなどが含まれます。テスターはこのリポジトリを新しいテスト マシンにプルするだけで、必要なあらゆる種類のリストにアクセスできるようになります。

VSCode Windows 64 ビットのダウンロード

VSCode Windows 64 ビットのダウンロード

Microsoft によって発売された無料で強力な IDE エディター