+
85
-

uniapp中如何将图片改成指定的尺寸并且全部显示原内容?

uniapp中如何将图片改成指定的尺寸并且全部显示原内容?

空白的地方用指定颜色填充

网友回复

+
8
-

以下是完整的解决方案:

<template>
  <view>
    <!-- 显示图片 -->
    <image 
      :src="imageUrl" 
      mode="aspectFit"
      style="width: 200px; height: 200px;"
    ></image>

    <!-- 用于绘制的 canvas,可以设置 hidden -->
    <canvas 
      canvas-id="myCanvas"
      :style="{width: '200px', height: '200px'}"
      hidden
    ></canvas>

    <!-- 导出按钮 -->
    <button @tap="exportImage">导出图片</button>
  </view>
</template>

<script>
export default {
  data() {
    return {
      imageUrl: '', // 你的图片地址
      canvasWidth: 200,
      canvasHeight: 200
    }
  },
  methods: {
    exportImage() {
      const ctx = uni.createCanvasContext('myCanvas', this)

      // 加载图片
      uni.getImageInfo({
        src: this.imageUrl,
        success: (image) => {
          // 计算缩放比例,保持原图比例
          const ratio = Math.min(
            this.canvasWidth / image.width,
            this.canvasHeight / image.height
          )

          // 计算居中位置
          const drawWidth = image.width * rati...

点击查看剩余70%

我知道答案,我要回答