drawHanBlock 绘制汉字方块,支持多行显示(6字以上时分成两行)
(hanFontSize, pinFontSize float64, idiom, target idiomJSON, exitPinyin ...string)
| 515 | |
| 516 | // drawHanBlock 绘制汉字方块,支持多行显示(6字以上时分成两行) |
| 517 | func drawHanBlock(hanFontSize, pinFontSize float64, idiom, target idiomJSON, exitPinyin ...string) image.Image { |
| 518 | class := len(target.Chars) |
| 519 | |
| 520 | // 确保切片长度一致 |
| 521 | if len(idiom.Chars) < class { |
| 522 | temp := make([]string, class) |
| 523 | copy(temp, idiom.Chars) |
| 524 | for i := len(idiom.Chars); i < class; i++ { |
| 525 | temp[i] = "?" |
| 526 | } |
| 527 | idiom.Chars = temp |
| 528 | } |
| 529 | if len(idiom.Pinyin) < class { |
| 530 | temp := make([]string, class) |
| 531 | copy(temp, idiom.Pinyin) |
| 532 | for i := len(idiom.Pinyin); i < class; i++ { |
| 533 | temp[i] = "" |
| 534 | } |
| 535 | idiom.Pinyin = temp |
| 536 | } |
| 537 | |
| 538 | chars := idiom.Chars |
| 539 | pinyin := idiom.Pinyin |
| 540 | |
| 541 | // 确定行数和每行字数 |
| 542 | rows := 1 |
| 543 | charsPerRow := class |
| 544 | if class > 6 { |
| 545 | rows = 2 |
| 546 | charsPerRow = (class + 1) / 2 |
| 547 | } |
| 548 | |
| 549 | ctx := gg.NewContext(1, 1) |
| 550 | _ = ctx.ParseFontFace(pinyinFont, pinFontSize) |
| 551 | pinWidth, pinHeight := ctx.MeasureString("w") |
| 552 | _ = ctx.ParseFontFace(pinyinFont, hanFontSize) |
| 553 | hanWidth, hanHeight := ctx.MeasureString("拼") |
| 554 | |
| 555 | space := int(pinHeight / 2) |
| 556 | blockPinWidth := int(pinWidth*6) + space |
| 557 | boxPadding := math.Min(math.Abs(float64(blockPinWidth)-hanWidth)/2, hanHeight*0.3) |
| 558 | |
| 559 | // 计算总宽度和高度 |
| 560 | width := space + charsPerRow*blockPinWidth + space |
| 561 | height := space + rows*(int(pinHeight+hanHeight+boxPadding*2)+space*2) + space |
| 562 | if len(exitPinyin) > 0 { |
| 563 | height = space + rows*(int(pinHeight+hanHeight+boxPadding*2+pinHeight)+space*2) + space |
| 564 | } |
| 565 | |
| 566 | ctx = gg.NewContext(width, height) |
| 567 | ctx.SetColor(color.RGBA{255, 255, 255, 255}) |
| 568 | ctx.Clear() |
| 569 | |
| 570 | for i := range class { |
| 571 | // 边界检查 |
| 572 | if i >= len(chars) || i >= len(pinyin) || i >= len(target.Pinyin) || i >= len(target.Chars) { |
| 573 | break |
| 574 | } |