前言

头像是我们在这社交平台上的一个对外的形象,让自己的头像更加独特可以加深其他人对咱们的第一印象。

尤其是遇到一些特别的节日,如国庆、中秋等等,可以通过给头像加特殊的边框来表达一份特殊的情感!!!

接下来,将会详细介绍如何制作个性化头像生成微信小程序,让大家都能够自己实现上面的想法!!!

首先一起来看看最终实现的个性化头像生成效果:

一、核心功能设计

 该小程序想要实现的是给微信头像或者选择相册中的照片加上个性化边框,所以拆解需求后,整理的核心功能如下:

  1. 授权登录获取头像及昵称
  2. 选择相册中的图片
  3. 选择个性化边框
  4. 合并选择的图片以及边框生成个性化头像
  5. 保存头像

二、实现步骤

首先新建一个空白的小程序项目,详细步骤可以参考之前的系列Python+微信小程序开发文章。

1.建立index界面

首先新建pages/index/index文件夹。

在pages/index/index.wxml中进行页面设计:

<!--pages/index/index.wxml-->
<view wx:if="{{canIUse}}">
    <view class='header'>
        <view class="userinfo-avatar">
            <open-data type="userAvatarUrl"></open-data>
        </view>
    </view>
    <view class="content">
        <view>申请获取以下权限</view>
        <text>获得您的公开信息(昵称,头像等)</text>
    </view>
    <button wx:if="{{canIUse}}" class="loginBtn" type="primary"  lang="zh_CN" bindtap="bindGetUserProfile" >
        授权登录
    </button>
</view>

在pages/index/index.wxss中设置样式:

/* pages/index/index.wxss */

.header {
    position: relative;
    margin: 90rpx 0rpx 90rpx 50rpx;
    width: 650rpx;
    height: 320rpx;
    color: #fff;
    display: flex;
    flex-direction: column;
    align-items: center;     /*居中对齐弹性盒子当中的各项元素*/
    border-bottom: 1px solid #ccc;
  }
  .userinfo-avatar {
    overflow:hidden;
    display: block;
    width: 160rpx;
    height: 160rpx;
    margin: 20rpx;
    margin-top: 50rpx;
    border-radius: 50%;
    border: 2px solid #fff;
    box-shadow: 3px 3px 10px rgba(0, 0, 0, 0.2);
  }
  .content {
      margin-left: 50rpx;
      margin-bottom: 90rpx;
  }
  .content text {
      display: block;
      color: #9d9d9d;
      margin-top: 40rpx;
  }
  .loginBtn {
      border-radius: 80rpx;
      margin: 100rpx 120rpx;
      font-size: 35rpx;
  }

然后在 pages/index/index.js 定义函数功能:

主要是就是通过bindGetUserProfile函数授权登录获取头像以及昵称

bindGetUserProfile(e)     //当用户点击授权登录按钮触发 bindGetUserInfo函数
{
  var that=this
  wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
      success: (res) => {
      console.log(res.userInfo)
      var avantarurl=res.userInfo.avatarUrl; 
      wx.navigateTo({
        url: '../../pages/avantarGenerate/avantarGenerate?url='+ avantarurl ,
      })
      },
      fail:(res)=>{
        console.log(1)
      }
    })
    
},

其中 wx.navigateTo({ })实现页面导航。

界面效果:

2.建立avantarGenerate界面

首先新建pages/avantarGenerate/avantarGenerate文件夹。

在pages/index/index.wxml中进行页面设计:

<!--pages/avantar/avantar.wxml-->
<!-- 画布大小按需定制 这里我按照背景图的尺寸定的  -->
<canvas canvas-id="shareImg"></canvas>

<!-- 预览区域  -->
<view class='preview'>
  <image class="tag" src='{{prurl}}' mode='aspectFit'></image>
  <view class="bottomAll">
    <view class="tipTxt">1,点击喜欢的图案生成个性化头像</view>
    <view class="btnAll">
      <button wx:for="{{demoList}}" wx:key="key" class="btn" open-type="getUserInfo"
        plain='true' bindgetuserinfo="generateAvantar"
        data-k="{{item.key}}">
        <image src="{{item.img}}" class="demoImg" mode='widthFix'></image>
      </button>
    </view>
    <view class="tipTxt">2,点击保存头像到本地</view>
    <button bindtap='save' class="saveBtn">保存头像到本地</button>

  </view>

</view>

在pages/index/index.wxss中设置样式:

/* pages/avantar/avantar.wxss */

canvas {
    position: fixed;
    top: 0;
    left: 400px;
    width: 1125px;
    height: 1125px;
  }
  
  .tag {
    width: 200px;
    height: 200px;
    position: absolute;
    top: 30px;
    left: 20%;
    z-index: 3;
    border: 1px dashed rgba(9, 241, 79, 0.863);
  }
  
  .preview {
    width: 100%;
    height: 100%;
    background: gainsboro;
    position: absolute;
    z-index: 2;
  }
  
  .bottomAll {
    width: 100%;
    position: absolute;
    bottom: 80rpx;
    z-index: 3;
  }
  
  .btnAll {
    width: 100%;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
  }
  
  .btn {
    width: 107rpx;
    height: 107rpx;
    border: none;
    padding: 0;
    margin: 0;
  }
  
  .demoImg {
    width: 100%;
    height: 100%;
  }
  
  .saveBtn {
    border-radius: 20rpx;
    background: #faa755;
    color: white;
    margin: 20rpx;
  }
  
  .tipTxt {
    color: #f05b72;
    margin: 20rpx;
    font-size: 38rpx;
  }

然后在 pages/index/index.js 定义函数功能:

通过wx.chooseImage选择相册中的图片

    generateAvantar:function(e){
        let that = this
        let index=e.currentTarget.dataset.k
        wx.chooseImage({
          count: (0),
          success(res){
              console.log('本地图片已获取',res.tempFilePaths[0])
              that.drawImg(res.tempFilePaths[0],index)
          }
        })
    },

通过drawImg将图像和边框合并。 

   drawImg(avatarUrl, index) {
        this.setData({
          msg: index + "~~~" + avatarUrl
        })
    
        let that = this;
        wx.showLoading({
          title: '努力生成中...'
        })
        let promise1 = new Promise(function (resolve, reject) {
          wx.getImageInfo({
            src: avatarUrl,
            success: function (res) {
              console.log("promise1", res)
              resolve(res);
            }
          })
        });

        let promise2 = new Promise(function (resolve, reject) {
          wx.getImageInfo({
            src: `../../static/images/head${index}.png`,
            success: function (res) {
              resolve(res);
            },
          })
        });

        Promise.all([
          promise1, promise2
        ]).then(res => {
          //主要就是计算好各个图文的位置
          let num = 1125;
          that.setData({
            prurl: res[0].path
          })
          ctx.drawImage(res[0].path, 0, 0, num, num)
          ctx.drawImage('../../' + res[1].path, 0, 0, num, num)
          ctx.draw(false, () => {
            wx.canvasToTempFilePath({
              x: 0,
              y: 0,
              width: num,
              height: num,
              destWidth: num,
              destHeight: num,
              canvasId: 'shareImg',
              success: function (res) {
                console.log(res.tempFilePath);
                that.setData({
                  prurl: res.tempFilePath
                })
                wx.hideLoading()
              },
              fail: function (res) {
                wx.hideLoading()
              }
            })
          })
        })
      },

通过save函数保存图片。  

save: function () {
    var that = this
    wx.saveImageToPhotosAlbum({
    filePath: that.data.prurl,
    success(res) {
        wx.showModal({
        content: '图片已保存到相册,赶紧晒一下吧~',
        showCancel: false,
        confirmText: '好哒',
        confirmColor: '#72B9C3',
        success: function (res) {
            if (res.confirm) {
            console.log('用户点击确定');
            }
        }
        })
    }
    })
},

效果如下: 

三、总结

其实这个小程序实现起来并不是很难,只有一些简单的事件绑定。只需要了解一些小程序基本的api,就能够开发出来,大家有时间的可以去试试,后台我已经搭好了,大家可以直接使用,可以看看效果。

有疑问的记得留言哦,我会尽力解答的,本次教程的源码可以通过下方的链接获得。

更多推荐

个性化头像生成——微信小程序开发