C\#불규칙 창 을 만 드 는 4 가지 방법 에 대한 설명

9460 단어 C#불규칙 창
현재 C\#불규칙 창 을 만 드 는 것 은 어 려 운 일이 아 닙 니 다.다음 과 같이 요약 하 겠 습 니 다.
사용자 정의 창
일반적으로 원,타원 등 규칙 적 인 도형 이다.
방법:Form1 재 작성Paint 이벤트(Form 1 은 창의 이름),가장 간단 한 상황 은 다음 과 같 습 니 다.

System.Drawing.Drawing2D.GraphicsPath shape = new System.Drawing.Drawing2D.GraphicsPath(); 
shape.AddEllipse(0,0,this.Height, this.Width); 
this.Region = new Region(shape); 
창 을 다시 그 리 는 규칙 입 니 다.
2.배경 그림 을 이용 하여 실현
1.창의 배경 그림 을 설정 합 니 다.배경 그림 은 24 비트(24 포함 하지 않 음)이하 의 비트 맵(BMP 그림)이 고 Tansparency Key 의 값 을 설정 해 야 합 니 다.보통 배경 그림 의 배경 색,즉 불규칙 한 그림 을 만 들 때의 바탕색 을 설정 합 니 다.그림 에 없 는 색 으로 설정 합 니 다.
이런 방법 이 좋 지 않 은 점 은 배경 그림 이 반드시 16 자리 나 더 낮 아야 하고 클 라 이언 트 의 디 스 플레이 를 확보 해 야 한 다 는 것 이다.모니터 의 색상 깊이 설정 이 24 비트 이상 이면 Transparency Key 속성 이 어떻게 설정 되 든 창의 불투명 한 부분 에 표시 문제 가 발생 합 니 다.이러한 문 제 를 피 하려 면'디 스 플레이'제어 판 의 모니터 색상 깊이 설정 이 24 비트 이하 인지 확인 하 십시오.이러한 투명 한 기능 을 가 진 프로그램 을 개발 할 때 사용자 가 이 문 제 를 의식 하도록 해 야 한 다 는 것 을 명심 하 십시오.
실현 절 차 는 다음 과 같다.
1.새 윈도 우즈 응용 프로그램
2.창 을 선택 하고 BackgroundImage 속성 을 찾 습 니 다.새 창 을 열 려 면 아래 자원 가 져 오기 파일 을 선택 하고 불규칙 한 BMP 그림 을 선택 하 십시오.
3.창 에 있 는 Tansparency Key 를 찾 아 배경 그림 의 배경 색(예:노란색)으로 설정 합 니 다.
4.창의 FormBorderStyle 을 찾 아 none 으로 설정 합 니 다.즉,제목 표시 줄 을 표시 하지 않 습 니 다.
5.운행

2. 배경 그림 과 같은 도형 은 동적 으로 불 러 오고 비트 맵 을 옮 겨 다 니 며 불규칙 한 창 을 만 듭 니 다.그 원 리 는 이 렇 습 니 다.Form 의 load 이벤트 에 쓰 는 방법 은 창의 묘사 영역 을 변화 시 킵 니 다.
실현 절 차 는 다음 과 같다.
1.winform 프로그램 만 들 기
2.창의 Load 이 벤트 를 찾 아 더 블 클릭 으로 편집
3.작성 방법,주요 코드 는 다음 과 같 습 니 다:

class BitmapRegion 
{ 
  public BitmapRegion() 
  { } 
 
 
  /// <summary>  
  /// Create and apply the region on the supplied control 
  ///            (   button form) 
  /// </summary>  
  /// <param name="control">The Control object to apply the region to  </param>  
  /// <param name="bitmap">The Bitmap object to create the region from  </param>  
  public static void CreateControlRegion(Control control, Bitmap bitmap) 
  { 
    // Return if control and bitmap are null 
    //            
    if (control == null || bitmap == null) 
      return; 
 
    // Set our control''s size to be the same as the bitmap 
    //            
    control.Width = bitmap.Width; 
    control.Height = bitmap.Height; 
    // Check if we are dealing with Form here  
    //    form  
    if (control is System.Windows.Forms.Form) 
    { 
      // Cast to a Form object 
      //     FORM 
      Form form = (Form)control; 
      // Set our form''s size to be a little larger that the bitmap just  
      // in case the form''s border style is not set to none in the first place  
      // FORM   FormBorderStyle  NONE ,  FORM                
      form.Width = control.Width; 
      form.Height = control.Height; 
      // No border  
      //     
      form.FormBorderStyle = FormBorderStyle.None; 
      // Set bitmap as the background image  
      //             
      form.BackgroundImage = bitmap; 
      // Calculate the graphics path based on the bitmap supplied  
      //              
      GraphicsPath graphicsPath = CalculateControlGraphicsPath(bitmap); 
      // Apply new region  
      //       
      form.Region = new Region(graphicsPath); 
    } 
    // Check if we are dealing with Button here  
    //    button  
    else if (control is System.Windows.Forms.Button) 
    { 
      // Cast to a button object  
      //      button 
      Button button = (Button)control; 
      // Do not show button text  
      //   button text 
      button.Text = ""; 
 
      // Change cursor to hand when over button  
      //   cursor style 
      button.Cursor = Cursors.Hand; 
      // Set background image of button  
      //  button      
      button.BackgroundImage = bitmap; 
 
      // Calculate the graphics path based on the bitmap supplied  
      //              
      GraphicsPath graphicsPath = CalculateControlGraphicsPath(bitmap); 
      // Apply new region  
      //       
      button.Region = new Region(graphicsPath); 
    } 
  } 
  /// <summary>  
  /// Calculate the graphics path that representing the figure in the bitmap  
  /// excluding the transparent color which is the top left pixel.  
  /// //              
  /// </summary>  
/// <param name="bitmap">The Bitmap object to calculate our graphics path from</param>  
  /// <returns>Calculated graphics path</returns>  
  private static GraphicsPath CalculateControlGraphicsPath(Bitmap bitmap) 
  { 
    // Create GraphicsPath for our bitmap calculation  
    //   GraphicsPath 
    GraphicsPath graphicsPath = new GraphicsPath(); 
    // Use the top left pixel as our transparent color  
    //                   
    Color colorTransparent = bitmap.GetPixel(0, 0); 
    // This is to store the column value where an opaque pixel is first found.  
  // This value will determine where we start scanning for trailing opaque pixels. 
    //       X 
    int colOpaquePixel = 0; 
    // Go through all rows (Y axis)  
    //      (Y  ) 
    for (int row = 0; row < bitmap.Height; row++) 
    { 
      // Reset value  
      //   
      colOpaquePixel = 0; 
      // Go through all columns (X axis)  
      //     (X  ) 
      for (int col = 0; col < bitmap.Width; col++) 
      { 
    // If this is an opaque pixel, mark it and search for anymore trailing behind  
        //               ,       
        if (bitmap.GetPixel(col, row) != colorTransparent) 
        { 
          // Opaque pixel found, mark current position 
          //     
          colOpaquePixel = col; 
       // Create another variable to set the current pixel position  
          //            
          int colNext = col; 
        // Starting from current found opaque pixel, search for anymore opaque pixels  
      // trailing behind, until a transparent  pixel is found or minimum width is reached  
          ///          ,        ,               
        for (colNext = colOpaquePixel; colNext < bitmap.Width; colNext++) 
            if (bitmap.GetPixel(colNext, row) == colorTransparent) 
              break; 
      // Form a rectangle for line of opaque  pixels found and add it to our graphics path  
          //       graphics path 
      graphicsPath.AddRectangle(new Rectangle(colOpaquePixel, row, colNext - colOpaquePixel, 1)); 
          // No need to scan the line of opaque pixels just found  
          col = colNext; 
        } 
      } 
    } 
    // Return calculated graphics path  
    return graphicsPath; 
  } 
} 
4.실행

3.라 이브 러 리 호출 실현
주로 좌표 에 따라 창 을 그립 니 다.
코드 는 다음 과 같 습 니 다:

public Form3() 
    { 
      InitializeComponent(); 
      //        
      POINTAPI[] poin; 
      poin = new POINTAPI[5]; 
      poin[0].x = 90; 
      poin[0].y = 90; 
      poin[1].x = this.Width; 
      poin[1].y = 0; 
      poin[2].x = Width; 
      poin[2].y = this.Height / 2; 
      poin[3].x = Width / 2; 
      poin[3].y = Height / 2; 
      poin[4].x = 0; 
      poin[4].y = Width; 
      Boolean flag = true; 
      IntPtr hRgn = CreatePolygonRgn(ref poin[0], 8, 1); 
      SetWindowRgn(this.Handle, hRgn, ref flag); 
      this.BackColor = Color.BurlyWood; 
    } 
    [StructLayout(LayoutKind.Sequential)] 
    private struct POINTAPI 
    { 
      internal int x; 
      internal int y; 
    } 
    [DllImport("gdi32.dll")] 
 private static extern IntPtr CreatePolygonRgn(ref POINTAPI lpPoint,int nCount,int nPolyFillMode); 
    [DllImport("user32.dll")] 
 private static extern IntPtr SetWindowRgn(IntPtr hWnd,IntPtr hRgn, ref Boolean bRedraw); 
    //         
    [DllImport("user32.dll")] 
private static extern int SetWindowPos(IntPtr hwnd,int hWndInsertAfter,int x,int y,int cx,int cy,int wFlags); 
    private void Start_Btn_Click(object sender, EventArgs e) 
    {//        
      SetWindowPos(this.Handle, -1, 0, 0, 0, 0, 1); 
    } 
    private void button1_Click(object sender, EventArgs e) 
    { 
      //           
      SetWindowPos(this.Handle, -1, 0, 0, 0, 0, 0); 
    } 
물론 창 동작 도 사용자 정의 할 수 있 습 니 다.예 를 들 어 특정한 궤적 에 따라 다음 코드 의 BackgroundForm 프로그램 에서 테스트 를 해 보 았 습 니 다.효과 가 좋 습 니 다.다음은 이 프로그램의 효과 그림 입 니 다. 

코드 는.Net 2.0 이 고 다른 버 전 으로 변환 할 수 있 으 며 메 인 프로그램 만 실행 하면 됩 니 다.
이상 의 네 가지 방법 은 유리 하고 폐단 도 있 으 니 의견 을 제시 하거나 더 좋 은 해결 방안 을 제시 하 시기 바 랍 니 다.

좋은 웹페이지 즐겨찾기