| 1 |
## How to use custom shape |
| 2 |
|
| 3 |
[Source Code](../../example/with-custom-shape/main.go) |
| 4 |
|
| 5 |
first step, you must define your own shape to QRCode, which consists of two part: |
| 6 |
* normal cell (of course, there are many types, separator, timing, alignment patter, data, format and version etc) |
| 7 |
* finder cell (to help recognizer to locate the matrix's position) |
| 8 |
|
| 9 |
<img src="../../assets/qrcode_structure.png" align="center" width="50%" /> |
| 10 |
|
| 11 |
```go |
| 12 |
type IShape interface { |
| 13 |
// Draw to fill the IShape of qrcode. |
| 14 |
Draw(ctx *DrawContext) |
| 15 |
|
| 16 |
// DrawFinder to fill the finder pattern of QRCode, what's finder? google it for more information. |
| 17 |
DrawFinder(ctx *DrawContext) |
| 18 |
} |
| 19 |
``` |
| 20 |
|
| 21 |
> Notice: |
| 22 |
> |
| 23 |
> if you must be careful to design finder's shape, otherwise qrcode could not be recognized. |
| 24 |
> |
| 25 |
|
| 26 |
|
| 27 |
Now, if you're define your shape like this: |
| 28 |
|
| 29 |
```go |
| 30 |
func newShape(radiusPercent float64) qrcode.IShape { |
| 31 |
return &smallerCircle{smallerPercent: radiusPercent} |
| 32 |
} |
| 33 |
|
| 34 |
// smallerCircle use smaller circle to qrcode. |
| 35 |
type smallerCircle struct { |
| 36 |
smallerPercent float64 |
| 37 |
} |
| 38 |
|
| 39 |
func (sc *smallerCircle) DrawFinder(ctx *qrcode.DrawContext) { |
| 40 |
// use normal radius to draw finder for that qrcode image can be recognized. |
| 41 |
backup := sc.smallerPercent |
| 42 |
sc.smallerPercent = 1.0 |
| 43 |
sc.Draw(ctx) |
| 44 |
sc.smallerPercent = backup |
| 45 |
} |
| 46 |
|
| 47 |
func (sc *smallerCircle) Draw(ctx *qrcode.DrawContext) { |
| 48 |
w, h := ctx.Edge() |
| 49 |
upperLeft := ctx.UpperLeft() |
| 50 |
color := ctx.Color() |
| 51 |
|
| 52 |
// choose a proper radius values |
| 53 |
radius := w / 2 |
| 54 |
r2 := h / 2 |
| 55 |
if r2 <= radius { |
| 56 |
radius = r2 |
| 57 |
} |
| 58 |
|
| 59 |
// 80 percent smaller |
| 60 |
radius = int(float64(radius) * sc.smallerPercent) |
| 61 |
|
| 62 |
cx, cy := upperLeft.X+w/2, upperLeft.Y+h/2 // get center point |
| 63 |
ctx.DrawCircle(float64(cx), float64(cy), float64(radius)) |
| 64 |
ctx.SetColor(color) |
| 65 |
ctx.Fill() |
| 66 |
|
| 67 |
} |
| 68 |
``` |
| 69 |
|
| 70 |
Finally, you can use your shape. |
| 71 |
|
| 72 |
```go |
| 73 |
func main() { |
| 74 |
shape := newShape(0.7) |
| 75 |
qrc, err := qrcode.New("with-custom-shape", qrcode.WithCustomShape(shape)) |
| 76 |
if err != nil { |
| 77 |
panic(err) |
| 78 |
} |
| 79 |
|
| 80 |
err = qrc.Save("./smaller.png") |
| 81 |
if err != nil { |
| 82 |
panic(err) |
| 83 |
} |
| 84 |
} |
| 85 |
``` |