Android实现特定形状的图片

https://blog.csdn.net/YX_BB/article/details/104561359
在上篇文章中,我们实现了圆形图片圆角图片,基本上已经满足了日常开发中的需要。那如果想要更多的图形效果该怎么办呢?与我们在现实中的绘图方式一致,用笔(Paint)在纸(Canvas)上按照一定的路径(Path),即可形成特定的图画。一个图形的Path是固定,所以,我们可以通过改变Paint和Canvas来实现想要的效果。如下
在这里插入图片描述

这里以心形图片为例,展示几种不同的实现方法,首先先实现心形图片的Path。

公式:t 表示点(x,y)在坐标系中的角度
x = 16 sin^3 t
y = 13 cos t - 5 cos 2t - 2 cos 3t - cos 4t

   /**
     * 心形曲线
     */
    private Path getHeartPath() {
   
        int n = 100;
        // 计算缩放比例
        float scale = getWidth() / 17f / 2f;
        // 将360度平均分为 100份,每个弧度对应一个点
        float interval = (float) (2 * Math.PI / 100);
        // 定义初始弧度degree
        float degree = 0;
        Point[] points = new Point[n];
        for (int i = 0; i < n; i++) {
   
            // 根据心形曲线公式,计算出每个弧度对应的点的坐标
            // 当degree = 90度的时候,x取最大值16。当degree = 180度的时候,y取最小值 -17。
            // 即保证y * scale * 17 * 2 = height的时候,曲线的与控件相切,以此计算出scale的值
            float x = (float) ((16 * Math.pow(Math.sin(degree), 3)) * scale);
            float y = (float) ((13 * Math.cos(degree) - 5 * Math.cos(2 * degree) - 2 * Math.cos(3 * degree) - Math.cos(4 * degree)) * scale);
            points[i] = new Point(x + getWidth() / 2f, -y + getHeight() / 2f);
            degree = degree + interval;
        }
        // 连线
        Path path = new Path();
        path.moveTo(points[0].x, points[0].y);
        for (int i = 1; i < n; i++) {
   
            path.lineTo(points[i].x, points[i].y);
        }
    
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值