Я пытаюсь воссоздать метку с помощью Vb.net
У меня есть этот ярлык, который я хочу воссоздать:
Что я сделал до сих пор:
Я пытался изменить строки, но не мог сделать так, я даже не знаю, как расположить или переместить или добавить новый столбец или строки.
Код, который я нашел в Интернете:
Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
Dim ht As Single = 7 ' Table Height
Dim wt As Single = 5 ' Table Width
Dim r As Integer = 15, c As Integer = 2 ' Rows and Cols in Table
Dim Cht As Single ' Cell Height
Dim lst As Single ' last line drawn
Dim i As Integer
Dim p As Pen
Cht = CSng(Math.Round(ht / r, 2)) * c
lst = 0.5F + Cht ' 0.5->default margin
p = New Pen(Color.Black, 0.025F)
e.Graphics.PageUnit = GraphicsUnit.Inch
e.Graphics.DrawRectangle(p, 0.5F, 0.5F, wt, ht) ' border of the table
p.Color = Color.Blue
For i = 0 To CInt(r / c) - 1 ' lines in the table
e.Graphics.DrawLine(p, 0.5F, lst, 0.5F + wt, lst)
lst += Cht
Next
End Sub
Я потерялся, я не знаю, как создать подобный ярлык. Как лучше всего это сделать?
@AndrewMortimer, спасибо за ваш ответ, но я сказал там, я не знаю, как с этим справиться.
DrawRectangle рисует внешнюю черную рамку. Затем DrawLine рисует горизонтальные синие линии. Посмотрите справку по этим двум методам, и вы увидите, что нужно изменить, чтобы сделать линии вертикальными или нарисовать другие прямоугольники.
Для внешнего прямоугольника со скругленными углами может быть полезно следующее: stackoverflow.com/questions/33853434/…
Вместо того, чтобы создавать это с помощью кода, вы можете Используйте элемент управления WinForms ReportViewer или Crystal Report создавать и печатать свои отчеты.
Следующее поможет вам приступить к созданию этикетки, изображенной на вашем OP.
Я буду использовать проект приложения Windows Forms (.NET Framework) с формой с именем Form1
.
Добавьте следующие операторы Imports:
Imports System.Drawing.Drawing2D
Imports System.Drawing.Printing
Чтобы нарисовать прямоугольник со скругленными углами, мы преобразуем код из здесь в VB.NET.
КруглыйПрямой:
Public Function RoundRect(bounds As Rectangle, radius1 As Integer, radius2 As Integer, radius3 As Integer, radius4 As Integer) As GraphicsPath
Dim diameter1 As Integer = radius1 * 2
Dim diameter2 As Integer = radius2 * 2
Dim diameter3 As Integer = radius3 * 2
Dim diameter4 As Integer = radius4 * 2
Dim arc1 As Rectangle = New Rectangle(bounds.Location, New Size(diameter1, diameter1))
Dim arc2 As Rectangle = New Rectangle(bounds.Location, New Size(diameter2, diameter2))
Dim arc3 As Rectangle = New Rectangle(bounds.Location, New Size(diameter3, diameter3))
Dim arc4 As Rectangle = New Rectangle(bounds.Location, New Size(diameter4, diameter4))
Dim path As GraphicsPath = New GraphicsPath()
'arc - top left
If radius1 = 0 Then
path.AddLine(arc1.Location, arc1.Location)
Else
path.AddArc(arc1, 180, 90)
End If
'arc - top right
arc2.X = bounds.Right - diameter2
If radius2 = 0 Then
path.AddLine(arc2.Location, arc2.Location)
Else
path.AddArc(arc2, 270, 90)
End If
'arc - bottom right
arc3.X = bounds.Right - diameter3
arc3.Y = bounds.Bottom - diameter3
If radius3 = 0 Then
path.AddLine(arc3.Location, arc3.Location)
Else
path.AddArc(arc3, 0, 90)
End If
'arc - bottom left
'arc4.X = bounds.Right - diameter4
arc4.Y = bounds.Bottom - diameter4
arc4.X = bounds.Left
If radius4 = 0 Then
path.AddLine(arc4.Location, arc4.Location)
Else
path.AddArc(arc4, 90, 90)
End If
path.CloseFigure()
Return path
End Function
Примечание: приведенный ниже код демонстрирует, как рисовать внешний прямоугольник, а также первую строку. Также показано, как писать текст и использовать Строка измерения для помощи в расчете позиций.
CreateProductLabel:
Private Sub CreateProductLabel(g As Graphics)
'ToDo: add (additional) desired code
Dim widthOuter As Integer = 600 'width of outer rectangle
Dim heightOuter As Integer = 325 'height of outer rectangle
Dim heightRow1 As Single = 80 'height of row 1
Dim xPosRightRow1Col1 As Single = 200 'x-position of row1, column 1
Dim xPosRightRow1Col2 As Single = 400 'x-position of row1, column 2
'specifying '0', indicates to use the smallest width possible
Using penDimGray As Pen = New Pen(Color.DimGray, 0)
'create rectangle for outer border
Dim outerRect As Rectangle = New Rectangle(0, 0, widthOuter, heightOuter)
'draw outer rectangle
Using path As GraphicsPath = RoundRect(outerRect, 10, 10, 10, 10)
g.DrawPath(penDimGray, path)
End Using
'draw horizontal line
g.DrawLine(penDimGray, New PointF(0, heightRow1), New PointF(outerRect.Width, heightRow1))
'draw vertical line - right side of row1, col 1
g.DrawLine(penDimGray, New PointF(xPosRightRow1Col1, 0), New PointF(xPosRightRow1Col1, heightRow1))
'draw vertical line - right side of row1, col 2
g.DrawLine(penDimGray, New PointF(xPosRightRow1Col2, 0), New PointF(xPosRightRow1Col2, heightRow1))
End Using
'size of the string(s); the height/width will be used in calculations
Dim sizeProductionDate As SizeF = New SizeF() 'initialize
Dim sizeShipper As SizeF = New SizeF() 'initialize
Dim sizeCosigner As SizeF = New SizeF() 'initialize
'draw text - headings
Using penBlack As Pen = New Pen(Color.Black, 2)
Using fontArial9Bold As Font = New Font("Arial", 9, FontStyle.Bold)
Using brush As SolidBrush = New SolidBrush(Color.Black)
'draw strings
g.DrawString("Shipper:", fontArial9Bold, brush, 5.0F, 2.0F)
g.DrawString("Cosigner:", fontArial9Bold, brush, xPosRightRow1Col1 + 2.0F, 2.0F)
'determine size of specified string
'the size (height/width) will be used in calculations below
sizeShipper = g.MeasureString("Shipper:", fontArial9Bold)
sizeCosigner = g.MeasureString("Cosigner:", fontArial9Bold)
End Using
End Using
Using fontArial8Bold As Font = New Font("Arial", 8, FontStyle.Bold)
Using brush As SolidBrush = New SolidBrush(Color.Black)
'draw String - Production Date
g.DrawString("Production Date:", fontArial8Bold, brush, xPosRightRow1Col2 + 2.0F, 2.0F)
'determine size of specified string
'the size (height/width) will be used in calculations below
sizeProductionDate = g.MeasureString("Production Date:", fontArial8Bold)
'draw string - Data de Producao
'this string Is positioned at the same Y-position, but for the X-position, add the height of the previous string
g.DrawString("Data de Producao", fontArial8Bold, brush, xPosRightRow1Col2 + 2.0F, 2.0F + sizeProductionDate.Height)
End Using
End Using
End Using
'draw product label information
Using penBlack As Pen = New Pen(Color.Black, 1)
Using fontArial9Regular As Font = New Font("Arial", 9, FontStyle.Regular)
Using brush As SolidBrush = New SolidBrush(Color.Black)
'draw strings
g.DrawString("A 1 VERDE LIMITADA", fontArial9Regular, brush, 5.0F + sizeShipper.Width, 2.0F)
g.DrawString("Plydor Seafood Limited", fontArial9Regular, brush, xPosRightRow1Col1 + 2.0F + sizeCosigner.Width, 2.0F)
End Using
End Using
End Using
End Sub
Примечание: для создания QR-кода можно использовать пакет NuGet, например QRКодер.
Для тестирования следуйте приведенным ниже инструкциям, чтобы нарисовать Panel
и/или распечатать с помощью PrintDocument
.
Откройте обозреватель решений
Открыть окно свойств
Добавьте Panel
к Form1 (имя: Panel1; Размер: 615, 340)
Подпишись на Paint
событие
Добавьте PrintDocument
к Form1 (имя: PrintDocument1)
Подпишись на Paint
событие
Добавьте Button
в форму (имя: btnPrint)
Подпишись на Click
событие
использование (Панель):
Private Sub Panel1_Paint(sender As Object, e As PaintEventArgs) Handles Panel1.Paint
CreateProductLabel(e.Graphics)
End Sub
использование (ПечатьДокумента):
Private Sub btnPrint_Click(sender As Object, e As EventArgs) Handles btnPrint.Click
PrintDocument1.Print()
End Sub
Private Sub PrintDocument1_PrintPage(sender As Object, e As PrintPageEventArgs) Handles PrintDocument1.PrintPage
CreateProductLabel(e.Graphics)
End Sub
Вот как выглядит Форма:
Ресурсы:
Похоже, вы неплохо продвигаетесь. Просто продолжайте с вертикальными и горизонтальными линиями, и вы доберетесь туда.