【ShareCode | 微信小程序】Text2Image

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jkol12/article/details/84345911

源码&视频: https://zhaoshuquan.com/posts/3

今天给大家分享如何制作一个Text2Image微信小程序。
text2image.gif

参考

主要功能

  • 添加文字
  • 选择背景
  • 选择字体大小
  • 生成图片
  • 保存图片到相册

步骤

  1. 创建项目
  2. 导入weui for 小程序样式库
  3. 添加text2image页面
  4. 添加布局
  5. 添加逻辑
  6. 完成 & 测试

创建项目

创建项目

导入weui for 小程序样式库

  1. 下载weui for 小程序样式文件
    https://github.com/Tencent/weui-wxss
  2. 将weui.wxss添加到项目中
    weui.wxss
  3. 引入全局样式
// app.wxss
@import '/src/wxss/weui.wxss';

添加text2image页面

// app.json
pages: [
  'pages/text2image/text2image',
  ...
]

添加以上代码,注意新页面放在pages数组第一个,确保小程序的首页为text2image,修改完之后并保存,添加新页面为下图时就成功了!
text2image页面

添加布局

<!--pages/text2image/text2image.wxml-->

<view class="page">
  <view class="page__bd">
    <view class="weui-cells__title">内容</view>
    <view class="weui-cells weui-cells_after-title">
      <view class="weui-cell">
          <view class="weui-cell__bd">
            <textarea class="weui-textarea" bindinput='typeNewContent' value="{{content}}" placeholder="请输入文本"/>
          </view>
      </view>
    </view>

    <view class="weui-cells__title">生成图片</view>
    <view class="weui-cells weui-cells_after-title">
      <canvas style="width:{{windowWidth}}px;height:{{contentHeight}}px" canvas-id="myCanvas"></canvas>
    </view>

    <view class="weui-cells__title">设置</view>
    <view class="weui-cells weui-cells_after-title weui-btn-area">
      <button type="primary" bindtap="chooseBackgroundImage">选择背景图片</button>

      <view class="section">
        <view class="section__title">选择文字颜色</view>
        <picker bindchange="bindPickerChange" value="{{fontColorIndex}}" range="{{fontColors}}">
          <view class="picker">
            当前选择:{{fontColors[fontColorIndex]}}
          </view>
        </picker>
      </view>
    </view>
    
    <view class="weui-btn-area">
      <button type="primary" bindtap="savePic" wx:if="{{hasGenerate}}">保存图片</button>
    </view>
  </view>
</view>
// pages/text2image/text2image.wxss

page {
  background-color: #F8F8F8;
}

界面

添加逻辑

设置data

// pages/text2image/text2image.js

data: {
    windowWidth: 0, // 窗口宽度
    contentHeight: 0, // 内容高度
    content: '', // 内容
    lineHeight: 30, // 行高 
    fontColorIndex: 0, // 当前字体颜色
    fontColors: [
      'black',
      'red',
      'white',
      'green'
    ], // 字体颜色列表
    backgroundImage: '../../src/images/leaves.png', // 背景图片
    hasGenerate: false, // 是否已经生成图片
},

导入背景图片

leaves.png
背景图片目录

获取窗口宽度

// pages/text2image/text2image.js
onLoad: function (options) {
    let that = this;

    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          windowWidth: res.windowWidth
        })
      }
    });
},

解析文字内容

// pages/text2image/text2image.js

parseContent: function () {
    let that = this;

    let i = 0;
    let lineNum = 1;
    let thinkStr = '';
    let thinkList = [];
    for (let item of that.data.content) {
      if (item === '\n') {
        thinkList.push(thinkStr);
        thinkList.push('a');
        i = 0;
        thinkStr = '';
        lineNum += 1;
      } else if (i === 19) {
        thinkList.push(thinkStr);
        i = 1;
        thinkStr = item;
        lineNum += 1;
      } else {
        thinkStr += item;
        i += 1;
      }
    }

    thinkList.push(thinkStr);

    return thinkList;
  }

绘制背景

// pages/text2image/text2image.js

drawBackground: function (ctx) {
    ctx.drawImage(this.data.backgroundImage);
}

绘制文字

// pages/text2image/text2image.js

drawFont: function (ctx, content, height) {
    ctx.setFontSize(16);
    ctx.setFillStyle(this.data.fontColors[this.data.fontColorIndex]);
    ctx.setTextAlign('center');
    ctx.fillText(content, this.data.windowWidth / 2, height);
}

清空画布

// pages/text2image/text2image.js

clearCanvas: function (ctx, width, height) {
    ctx.clearRect(0, 0, width, height);
}

创建图片

// pages/text2image/text2image.js

createNewImg: function (thinkList) {
    let that = this;

    let lineNum = thinkList.length;

    let ctx = wx.createCanvasContext('myCanvas');

    this.clearCanvas(ctx, that.data.windowWidth, that.data.contentHeight);

    let height = 60;

    let contentHeight = (lineNum - 1) * that.data.lineHeight + 2 * height;

    that.setData({
      contentHeight: contentHeight
    });

    that.drawBackground(ctx, contentHeight);

    for (let item of thinkList) {
      if (item !== 'a') {
        that.drawFont(ctx, item, height);
        height += that.data.lineHeight;
      }
    }
    ctx.draw();
}

生成图片

// pages/text2image/text2image.js

generateImage: function() {
    let thinkList = this.parseContent();

    this.createNewImg(thinkList);

    this.setData({
      hasGenerate: true
    });
}

设置页面显示时生成图片

// pages/text2image/text2image.js
onShow: function(options) {
    this.generateImage();
}

这一步的目的是页面初始化页面数据。

绑定输入新内容事件

// pages/text2image/text2image.js

typeNewContent: function(e) {
    this.setData({
      content: e.detail.value.trim()
    });

    this.generateImage();
}

现在尝试在内容文本框中输入文字,文字会实时显示在下面的图片区域。

选择背景图片

// pages/text2image/textimage.js

chooseBackgroundImage: function () {
    let that = this;

    wx.chooseImage({
      success: function (res) {
        that.setData({
          backgroundImage: res.tempFilePaths[0]
        });

        that.generateImage();
      }
    })
},

从本地相册选择背景图片或使用照相机拍照,选择成功之后重新生成图片。

绑定选择字体颜色事件

// pages/text2image/text2image.js

bindPickerChange: function(e) {
    let that = this;

    that.setData({
      fontColorIndex: e.detail.value
    });

    that.generateImage();
},

点击选择文字颜色区域,即可进行颜色选择,可以在fontColors数组中添加 【更多预定义颜色】。

保存图片

// pages/text2image/text2image.js

savePic: function () {
    let that = this;
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: that.data.windowWidth,
      height: that.data.contentHeight,
      canvasId: 'myCanvas',
      success: function (res) {
        that.savePicToAlbum(res.tempFilePath);
      }
    }, this)
  },

  savePicToAlbum: function (tempFilePath) {
    let that = this;
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              wx.saveImageToPhotosAlbum({
                filePath: tempFilePath,
                success(res) {
                  wx.showToast({
                    title: '保存成功'
                  });
                },
                fail(res) {
                  console.log(res);
                }
              })
            },
            fail() {
              // 用户拒绝授权,打开设置页面
              wx.openSetting({
                success: function (data) {
                  console.log("openSetting: success");
                },
                fail: function (data) {
                  console.log("openSetting: fail");
                }
              });
            }
          })
        } else {
          wx.saveImageToPhotosAlbum({
            filePath: tempFilePath,
            success(res) {
              wx.showToast({
                title: '保存成功',
              });
            },
            fail(res) {
              console.log(res);
            }
          })
        }
      },
      fail(res) {
        console.log(res);
      }
    })
  }

点击保存图片按钮即可保存生成的图片。

猜你喜欢

转载自blog.csdn.net/jkol12/article/details/84345911