前言
微信后台生成海報一般都是一個模板寫死,然后就完事了,過了不久讓修改個模板,就又要看半天,還要考慮是否重新復制一份改一改,越來越多的重復代碼,全在一個圖片類里,然后就越來越亂。這兩天用設計模式處理了一下,讓以后修改模板,新增模板更舒服一點。有第三方好用的輕量級的實現,還請留言。感激!!
效果圖
快速上手
Maven pom文件引入【github直接clone源碼 更方便定制修改】
<!-- https://mvnrepository.com/artifact/com.github.quaintclever/easyposter -->
<dependency>
<groupId>com.github.quaintclever</groupId>
<artifactId>easyposter</artifactId>
<version>1.2</version>
</dependency>
Gradle
// https://mvnrepository.com/artifact/com.github.quaintclever/easyposter
compile group: 'com.github.quaintclever', name: 'easyposter', version: '1.2'
海報定義類
/**
* @author quaint
* @date 30 March 2020
* @since 1.0
*/
@EqualsAndHashCode(callSuper = true)
@Data
@Builder
public class SamplePoster extends AbstractDefaultPoster {
/**
* 背景圖
*/
@PosterBackground(width = 666,height = 365)
private BufferedImage backgroundImage;
/**
* 頭像
*/
@PosterImageCss(position = {27,27},width = 36, height = 36, circle = true)
private BufferedImage head;
/**
* 昵稱
*/
@PosterFontCss(position = {71,32}, color = {255,255,255})
private String nickName;
/**
* 廣告語
*/
@PosterFontCss(position = {27,70},center = true, size = 22, color = {255,255,255}, canNewLine={1,221,7})
private String slogan;
/**
* 主圖
*/
@PosterImageCss(position = {27,172},width = 168,height = 168)
private BufferedImage mainImage;
@Tolerate
public SamplePoster() {}
}
海報繪制
/**
* 繪制海報本地測試
* @author quaint
* @date 21 February 2020
* @since 1.0
*/
public class PosterTest {
public static void main(String[] args) throws Exception{
// 測試注解, 這里讀取圖片如果不成功,請查看target 或者 out 目錄下是否加載了資源。 如需使用,請引入spring core依賴
BufferedImage background = ImageIO.read(new ClassPathResource("image/yayi.png").getInputStream());
BufferedImage head = ImageIO.read(new ClassPathResource("image/headimage.jpg").getInputStream());
SamplePoster poster = SamplePoster.builder()
.backgroundImage(background)
.head(head)
.nickName("Quaint")
.slogan("命運多舛,痴迷淡然。揮別了青春,數不盡的車站。甘於平凡,卻不甘平凡地潰敗。")
.mainImage(head)
.build();
PosterDefaultImpl<SamplePoster> impl = new PosterDefaultImpl<>();
BufferedImage test = impl.annotationDrawPoster(poster).draw(null);
ImageIO.write(test,"png",new FileOutputStream("annTest.png"));
}
}
注解繪制效果圖
源碼閱讀
- 了解IO
- 了解awt
- 裝飾者設計模式
- 責任鏈設計模式
- 策略模式
- 建造者模式
感覺還不錯 的話記得投幣哦~