美文网首页
小程序音乐播放进度条

小程序音乐播放进度条

作者: Astep | 来源:发表于2019-06-17 15:16 被阅读0次

    在写这篇文章之前,笔者查看了多篇博客,无奈前辈大多只是贴了代码,没有清晰明了的注释,所以容易让新人看得云里雾里。这里,笔者在弄明白原理后,对代码进行了优化,决定写(总结)一篇清晰、明了的圆形进度条的实现,以便后人能快速搞懂。

    一、实现原理

    首先,我们来一个圆(黑色)。
    接着,再来两个半圆,将黑色的圆遮住。(为了演示,左右两侧颜色不一样)
    这时候,我们顺时针旋转右侧蓝色的半圆,下面的黑色圆就会暴露出来,比如我们旋转45度(12.5%),效果出来了。
    如果我们将蓝色的右半圆同样设置成灰色,看效果,一个12.5%的饼图就出来了!


    1.png 2.png 3.png 4.png

    OK,我们再旋转更大的度数试试,比如40%(144度),50%(180度),60%(216度)如下图。
    我们发现,旋转180度之后右半圆与左半圆重合了,如果再旋转,就会在右上角冒出来,显然不是我们想要的。


    5.png 6.png 7.png

    我们希望的是,继续旋转被黑色遮住。。。嗯。。。怎么做呢?

    我们将右侧的圆回归原位,把它刷成黑色(和底色一样),然后旋转左边的半圆(它在右侧半圆的更底层),这样,它就会被右侧半圆遮住了。好的,废话不多说,我们将左侧的半圆顺时针旋转45度,效果出来了。可以想象,继续旋转,180度的时候,就完全被右侧半圆遮住,而左侧底色全部暴露,这样100%显示出来了。


    8.png 9.png 10.png

    最后,加上一个白色的小圆,放在正中间就行了。

    好的,到这里,我们已经明白如何实现的了。

    wxml
    <view class="circle-bar">
      <view class="circle-bar-left" style='transform:rotate({{rightDeg}}deg)'></view>
      <view class="circle-bar-right" style='transform:rotate({{leftDeg}}deg);background-color:{{bgIShow?"#333":"#eee"}}'></view>
      <!-- 遮罩层,显示百分比 -->
      <view class="mask">{{percent}}%</view>
    </view>
    wxss
    page{
      background-color: pink;
    }
    .circle-bar {
      width: 200rpx;
      height: 200rpx;
      position: relative;
      border-radius: 50%;
      background-color: #333;
    }
    
    .circle-bar-left, .circle-bar-right {
      width: 100%;
      height: 100%;
      background-color: #eee;
    }
    
    .circle-bar-right {
      clip: rect(0, auto, auto, 100rpx);
    }
    
    .circle-bar-left {
      clip: rect(0, 100rpx, auto, 0);
    }
    
    .mask {
      width: 180rpx;
      height: 180rpx;
      display: flex;
      border-radius: 50%;
      align-items: center;
      justify-content: center;
      background-color: white;
    }
    
    .circle-bar >view {
      position: absolute;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      margin: auto;
      border-radius: 50%;
    }
     data: {
        percent: 0,
        bgIShow: false,
        rightDeg: 0,
        leftDeg: 0
      },
    
      /**
       * 生命周期函数--监听页面加载
       */
      onLoad: function(options) {
        let _this=this;
        setInterval(function(){
          _this.setData({
            percent: ++_this.data.percent
          })
          _this.newx();
        },500)
      },
      newx() {
        let percent = this.data.percent;
        if (percent <= 50) {
          this.setData({
            bgIShow: false,
            leftDeg: parseInt(percent * 3.6)
          })
        } else {
          this.setData({
            bgIShow: true,
            leftDeg:0,
            rightDeg: parseInt((percent - 50) * 3.6)
          })
        }
      }
    
    

    相关文章

      网友评论

          本文标题:小程序音乐播放进度条

          本文链接:https://www.haomeiwen.com/subject/gxbafctx.html