使用GDI+ MeasureString方法计算显示 输入文本的长度

// stdafx.h : include file for standard system include files,
//  or project specific include files that are used frequently, but
//      are changed infrequently
//

#if !defined(AFX_STDAFX_H__660C12D0_6133_459C_B633_7A2DFC9FFD72__INCLUDED_)
#define AFX_STDAFX_H__660C12D0_6133_459C_B633_7A2DFC9FFD72__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#define VC_EXTRALEAN  // Exclude rarely-used stuff from Windows headers

#ifndef ULONG_PTR
#define ULONG_PTR unsigned long*
#endif


#include          // MFC core and standard components
#include          // MFC extensions
#include         // MFC Automation classes
#include   // MFC support for Internet Explorer 4 Common Controls
#ifndef _AFX_NO_AFXCMN_SUPPORT
#include    // MFC support for Windows Common Controls
#endif // _AFX_NO_AFXCMN_SUPPORT


#include
using namespace Gdiplus;

#pragma comment(lib, "gdiplus.lib")

//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.

#endif // !defined(AFX_STDAFX_H__660C12D0_6133_459C_B633_7A2DFC9FFD72__INCLUDED_)

 

 

 

// MeasureStringTestDlg.h : header file
//

#if !defined(AFX_MEASURESTRINGTESTDLG_H__4887F642_8530_485A_8067_D30D1664AD2D__INCLUDED_)
#define AFX_MEASURESTRINGTESTDLG_H__4887F642_8530_485A_8067_D30D1664AD2D__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

/////////////////////////////////////////////////////////////////////////////
// CMeasureStringTestDlg dialog

class CMeasureStringTestDlg : public CDialog
{
// Construction
public:
 CMeasureStringTestDlg(CWnd* pParent = NULL); // standard constructor

// Dialog Data
 //{{AFX_DATA(CMeasureStringTestDlg)
 enum { IDD = IDD_MEASURESTRINGTEST_DIALOG };
  // NOTE: the ClassWizard will add data members here
 //}}AFX_DATA

 // ClassWizard generated virtual function overrides
 //{{AFX_VIRTUAL(CMeasureStringTestDlg)
 protected:
 virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
 //}}AFX_VIRTUAL

// Implementation
protected:
 HICON m_hIcon;

 // Generated message map functions
 //{{AFX_MSG(CMeasureStringTestDlg)
 virtual BOOL OnInitDialog();
 afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
 afx_msg void OnPaint();
 afx_msg HCURSOR OnQueryDragIcon();
 afx_msg void OnButton1();
 afx_msg void OnChangeEdit1();
 //}}AFX_MSG
 DECLARE_MESSAGE_MAP()

public:
 int GetShowIndex( CRect& rectEdit, wchar_t* pText, Font& font, StringFormat& sf);
};

//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.

#endif // !defined(AFX_MEASURESTRINGTESTDLG_H__4887F642_8530_485A_8067_D30D1664AD2D__INCLUDED_)

 

 

// MeasureStringTestDlg.cpp : implementation file
//

#include "stdafx.h"
#include "MeasureStringTest.h"
#include "MeasureStringTestDlg.h"
#include "GdiPlus.h"
#include "GdiPlusInit.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif


/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
 CAboutDlg();

// Dialog Data
 //{{AFX_DATA(CAboutDlg)
 enum { IDD = IDD_ABOUTBOX };
 //}}AFX_DATA

 // ClassWizard generated virtual function overrides
 //{{AFX_VIRTUAL(CAboutDlg)
 protected:
 virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
 //}}AFX_VIRTUAL

// Implementation
protected:
 //{{AFX_MSG(CAboutDlg)
 //}}AFX_MSG
 DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
 //{{AFX_DATA_INIT(CAboutDlg)
 //}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
 CDialog::DoDataExchange(pDX);
 //{{AFX_DATA_MAP(CAboutDlg)
 //}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
 //{{AFX_MSG_MAP(CAboutDlg)
  // No message handlers
 //}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CMeasureStringTestDlg dialog

CMeasureStringTestDlg::CMeasureStringTestDlg(CWnd* pParent /*=NULL*/)
 : CDialog(CMeasureStringTestDlg::IDD, pParent)
{
 //{{AFX_DATA_INIT(CMeasureStringTestDlg)
  // NOTE: the ClassWizard will add member initialization here
 //}}AFX_DATA_INIT
 // Note that LoadIcon does not require a subsequent DestroyIcon in Win32
 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CMeasureStringTestDlg::DoDataExchange(CDataExchange* pDX)
{
 CDialog::DoDataExchange(pDX);
 //{{AFX_DATA_MAP(CMeasureStringTestDlg)
  // NOTE: the ClassWizard will add DDX and DDV calls here
 //}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CMeasureStringTestDlg, CDialog)
 //{{AFX_MSG_MAP(CMeasureStringTestDlg)
 ON_WM_SYSCOMMAND()
 ON_WM_PAINT()
 ON_WM_QUERYDRAGICON()
 ON_BN_CLICKED(IDC_BUTTON1, OnButton1)
 ON_EN_CHANGE(IDC_EDIT1, OnChangeEdit1)
 //}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CMeasureStringTestDlg message handlers

BOOL CMeasureStringTestDlg::OnInitDialog()
{
 CDialog::OnInitDialog();

 // Add "About..." menu item to system menu.

 // IDM_ABOUTBOX must be in the system command range.
 ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
 ASSERT(IDM_ABOUTBOX < 0xF000);

 CMenu* pSysMenu = GetSystemMenu(FALSE);
 if (pSysMenu != NULL)
 {
  CString strAboutMenu;
  strAboutMenu.LoadString(IDS_ABOUTBOX);
  if (!strAboutMenu.IsEmpty())
  {
   pSysMenu->AppendMenu(MF_SEPARATOR);
   pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
  }
 }

 // Set the icon for this dialog.  The framework does this automatically
 //  when the application's main window is not a dialog
 SetIcon(m_hIcon, TRUE);   // Set big icon
 SetIcon(m_hIcon, FALSE);  // Set small icon
 
 // TODO: Add extra initialization here
 
 GdiplusStartupInput gdiplusStartupInput;
    ULONG_PTR           gdiplusToken;
    GdiplusStartup( &gdiplusToken, &gdiplusStartupInput, NULL );

 return TRUE;  // return TRUE  unless you set the focus to a control
}

void CMeasureStringTestDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
 if ((nID & 0xFFF0) == IDM_ABOUTBOX)
 {
  CAboutDlg dlgAbout;
  dlgAbout.DoModal();
 }
 else
 {
  CDialog::OnSysCommand(nID, lParam);
 }
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CMeasureStringTestDlg::OnPaint()
{
 if (IsIconic())
 {
  CPaintDC dc(this); // device context for painting

  SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

  // Center icon in client rectangle
  int cxIcon = GetSystemMetrics(SM_CXICON);
  int cyIcon = GetSystemMetrics(SM_CYICON);
  CRect rect;
  GetClientRect(&rect);
  int x = (rect.Width() - cxIcon + 1) / 2;
  int y = (rect.Height() - cyIcon + 1) / 2;

  // Draw the icon
  dc.DrawIcon(x, y, m_hIcon);
 }
 else
 {
  CDialog::OnPaint();
 }
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CMeasureStringTestDlg::OnQueryDragIcon()
{
 return (HCURSOR) m_hIcon;
}

void CMeasureStringTestDlg::OnButton1()
{
 // TODO: Add your control notification handler code here
 CString strText = "";
 GetDlgItem(IDC_EDIT1)->GetWindowText( strText );

 WCHAR m_awszFontName[64];
 ZeroMemory( m_awszFontName, sizeof(m_awszFontName) );
 const char* achFontFamlyName = ("Arial") ;
 MultiByteToWideChar(CP_ACP, 0, achFontFamlyName, -1, m_awszFontName, strlen(achFontFamlyName) );

 SolidBrush brush( Color( 255, 0, 0 ) );


 FontFamily fontFamily( m_awszFontName );
 Font font( &fontFamily, 14 );
 Graphics graphics(m_hWnd);

 CRect cRect;
    GetDlgItem(IDC_STDRAW)->GetWindowRect( &cRect );
 
    POINT point = cRect.TopLeft();

 ::ScreenToClient( m_hWnd, &point );

 StringFormat sf;
 sf.SetFormatFlags( StringFormatFlagsNoWrap | StringFormatFlagsMeasureTrailingSpaces );  
 sf.SetLineAlignment( StringAlignmentCenter ); //StringAlignmentNear StringAlignmentCenter
 sf.SetAlignment( StringAlignmentFar );

 WCHAR *pwszText = NULL;
 pwszText = new WCHAR[strText.GetLength() + 1];
 int nLen = MultiByteToWideChar( CP_ACP, 0, strText, -1, NULL, NULL );
 MultiByteToWideChar(CP_ACP,   0,   strText,   -1,   pwszText,   nLen);
 DWORD dwTextLen = wcslen(pwszText);
 RectF rectString;
 RectF rectStringBk;

 graphics.MeasureString( pwszText/*L"a"*/, -1, &font, PointF( (float)0, (float)0 ), &sf, &rectString );
 rectStringBk = rectString;

 CString strRectStringWidth = "";
 strRectStringWidth.Format("%f , %f ", rectString.Width, rectString.Height );
 GetDlgItem(IDC_EDIT2)->SetWindowText(strRectStringWidth);

 DWORD dwIndex = GetShowIndex( cRect, pwszText, font, sf );

 graphics.DrawString(pwszText + dwTextLen - dwIndex+1, -1, &font, RectF( (float)point.x, (float)point.y,
  cRect.Width(), cRect.Height()), &sf, &brush );

 delete []pwszText;
 pwszText = NULL;

}


int CMeasureStringTestDlg::GetShowIndex( CRect& rectEdit, wchar_t* pText, Font& font, StringFormat& sf)
{
 if ( NULL == pText)
 {
  return 0;
 }

 DWORD dwTextLen = wcslen( pText );
 DWORD dwIndex = 0;
 
 Graphics graphics(m_hWnd);   

 RectF rectString;
 rectString.Width = 0;
 
 for( int i = dwTextLen; i>=0; i--)
 {  
  if ( rectString.Width < (float)rectEdit.Width() )
  {
   dwIndex++;
   graphics.MeasureString( pText + dwTextLen - dwIndex , -1, &font, PointF( (float)0, (float)0 ), &sf, &rectString );
   
   if ( rectString.Width >  (float)rectEdit.Width() )
   {
    //还是采用上一次的
    dwIndex--;
    break;
   }
  }
  else
  {
   break;
  }
 }
 
 return dwIndex;
}

void CMeasureStringTestDlg::OnChangeEdit1()
{
 // TODO: If this is a RICHEDIT control, the control will not
 // send this notification unless you override the CDialog::OnInitDialog()
 // function and call CRichEditCtrl().SetEventMask()
 // with the ENM_CHANGE flag ORed into the mask.
 
 // TODO: Add your control notification handler code here
 RedrawWindow();
 OnButton1();
}

 

 

 

 

 

 

 

你可能感兴趣的:(MFC,c++,gdi+,mfc,dialog,initialization,microsoft,float)