Читаем Программирование КПК и смартфонов на .NET Compact Framework полностью

 FillPie(e.Graphics, new SolidBrush(Color.Green),

  120, 160, 100, 100, 46, 90);

 FillPie(e.Graphics, new SolidBrush(Color.Yellow),

  120, 160, 100, 100, 91, 120);

 FillPie(e.Graphics, new SolidBrush(Color.Blue),

  120, 160, 100, 100, 121, 260);

 FillPie(e.Graphics, new SolidBrush(Color.Red),

  120, 160, 100, 100, 261, 360);

}

Результат работы этой программы показан на рис. 6.2.

Рис. 6.2. Создание секторов

Создание фонового рисунка для формы

К сожалению, .NET Compact Framework не поддерживает свойство BackgroundImage, которое создает фоновый рисунок для формы. Но каждый программист может восполнить данный пробел, переопределяя метод OnPaint.

Нужно создать новый проект и разместить на форме какой-нибудь элемент управления, например кнопку. Кнопка не будет выполнять никаких функций. Она потребуется лишь для демонстрации технологии. Также надо добавить в проект изображение, которое будет использоваться в качестве фона для формы. В нашем примере картинка будет внедрена в программу как ресурс, хотя можно загрузить ее из обычного графического файла. Чтобы все работало так, как запланировано, необходимо переопределить метод OnPaint(). Новый код метода приведен в листинге 6.16.

Листинг 6.16

protected override void OnPaint(PaintEventArgs e) {

 // получим картинку из ресурсов Bitmap

 backgroundImage = new Bitmap(Assembly.GetExecutingAssembly().

  GetManifestResourceStream("BackgroundImageCS.sochicat.jpg"));


 e.Graphics.DrawImage(backgroundImage, this.ClientRectangle,

  new Rectangle(0, 0, backgroundImage.Width, backgroundImage.Height),

 GraphicsUnit.Pixel);

}

После запуска программы можно будет увидеть, что форма имеет фоновый рисунок, а кнопка расположена поверх фона (рис. 6.3).

Рис. 6.3. Заполнение фона формы своим рисунком

Копирование рисунка

Библиотека .NET Compact Framework 1.0 не поддерживает метод System.Drawing.Image.Clone, позволяющий создать точную копию картинки. Это ограничение легко обходится с помощью создания собственных методов. Кроме того, можно расширить возможности метода и добавить функциональность, позволяющую копировать часть картинки. Соответствующий код приведен в листинге 6.17.

Листинг 6.17

// Копируем всю картинку

protected Bitmap CopyBitmap(Bitmap source) {

 return new Bitmap(source);

}


// Копируем часть картинки

protected Bitmap CopyBitmap(Bitmap source, Rectangle part) {

 Bitmap bmp = new Bitmap(part.Width, part.Height);

 Graphics g = Graphics.FromImage(bmp);

 g.DrawImage(source, 0, 0, part, GraphicsUnit.Pixel);

 g.Dispose();

 return bmp;

}


private void button1_Click(object sender, EventArgs e) {

 Graphics g = CreateGraphics();

 Bitmap myBMP = new Bitmap(@"\windows\banner.gif");


 // Половина ширины картинки

 int left = myBMP.Size.Width / 2;

 // Копируем всю картинку Bitmap

 clone = CopyBitmap(myBMP);


 // копируем левую часть картинки

 Bitmap part =

  CopyBitmap(myBMP, new Rectangle(0, 0, left, myBMP.Size.Height));


 // Выводим три картинки по вертикали:

 // источник, копию и копию левой части

 int y = 10;


 // картинка-источник

 g.DrawImage(myBMP, 10, y);

 y += myBMP.Height + 10;


 // картинка-копия

 g.DrawImage(clone, 10, y);

 y += clone.Height + 10;


 // копия левой части картинки

 g.DrawImage(part, 10, y);

 y += part.Height + 10;

 g.Dispose();

}


Перейти на страницу:

Похожие книги

C++ Primer Plus
C++ Primer Plus

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

Программирование, программы, базы данных