1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

VBでお絵描きソフトを作成する

Last updated at Posted at 2017-11-29

モチベーション

手書きでレポートを出さないといけない授業があるけど、提出するには書いた紙をスキャナで2値化してpdfにして提出しないといけない。非常に面倒くさい。しかし幸運なことに教授は極度の弱視なので、簡単に偽造できそうな気がしてきたのでやってみる。まずは手書き文字を保存するためのお絵かきソフトを作る。

ソースコードVer1

Form1.vb
Imports System.Drawing
Imports System.Drawing.Drawing2D

Public Class Form1
    Private Sub PictureBox1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseMove
        Dim g As Graphics = sender.CreateGraphics()
        g.SmoothingMode = SmoothingMode.AntiAlias
        If e.Button = MouseButtons.Left Then
            g.FillEllipse(Brushes.Black, e.X, e.Y, 5, 5)
        ElseIf e.Button = MouseButtons.Right Then
            g.FillEllipse(Brushes.White, e.X, e.Y, 30, 30)
        End If
    End Sub
End Class

実行結果Ver1

描画間隔が遅くて紙に書く感覚で書くとこの有様↓

アンチエイリアス無し
2017-11-29 (1).png
どうにか滑らかに書けないかと思ってたらアンチエイリアスのオプションがあることに気づいたので、それっぽく見えるかな~って思って実行↓

アンチエイリアス有り
2017-11-29 (2).png

ましにはなったけどまだ全然ダメじゃん?
今になって、Windowsのペイントは超優秀だということに気づく。
もっと滑らかに書ける方法を探さなきゃ...

改善策

点を連続で描画して線に見せる方法から直線を連続で描く方法に替えてみる。

ソースコードVer2

Form1.vb
Imports System.Drawing
Imports System.Drawing.Drawing2D

Public Class Form1
    Dim X, Y As Integer '始点
    Dim flg As Boolean
    Dim rnd As New System.Random(1000)
    Private Sub PictureBox1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseMove
        Dim g As Graphics = sender.CreateGraphics()
        Dim liner As New Pen(Color.FromKnownColor(KnownColor.Black), rnd.Next(3, 6)) '線の太さを少し変えつつ描画する
        g.SmoothingMode = SmoothingMode.AntiAlias

        If e.Button = MouseButtons.Left Then
            If flg = True Then
                g.DrawLine(liner, X, Y, e.X, e.Y)
                flg = False
            End If
            flg = True
            X = e.X : Y = e.Y
        Else
            flg = False
        End If

        If e.Button = MouseButtons.Right Then
            g.FillEllipse(Brushes.White, e.X, e.Y, 30, 30)
        End If
    End Sub
End Class

実行結果Ver2

できた。なるほど。(jTakasuRyujiさんアドバイスありがとうございます。助かりました。)
2017-11-30.png

参考サイト

vb講座14 クリックイベントプロシージャを使ってお絵かきソフトを作成する

[Graphics オブジェクトの状態の管理]
(https://msdn.microsoft.com/ja-jp/library/sf4e5x7z(v=vs.110).aspx)

1
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?