草庐IT

android - 向 HexagonLoadingView 添加淡入淡出动画

coder 2023-12-02 原文

我使用了一个基于库的六边形加载器 https://github.com/Agraphie/hexagonloadingview . 但我需要与上述库略有不同的动画。 喜欢https://codepen.io/wuser/pen/BgPMqE

六边形 View 动画代码

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.View;

public class HexagonLoadingView extends View {

public static final int NUMBER_OF_HEXAGONS = 7;
/**
 * Constants for changing the number of appearance/disappearance of the hexagons. {@link
 * HexagonLoadingView#HEXAGON_UPPER_LEFT_APPEARANCE_POSITION} = 0 means the hexagon will start
 * appearing in the upper left corner. {@link HexagonLoadingView#HEXAGON_MIDDLE_MIDDLE_APPEARANCE_POSITION}
 * = 6 means this hexagon will appear last and disappear first.
 */
public static final int HEXAGON_UPPER_LEFT_APPEARANCE_POSITION = 0;
public static final int HEXAGON_UPPER_RIGHT_APPEARANCE_POSITION = 1;
public static final int HEXAGON_MIDDLE_LEFT_APPEARANCE_POSITION = 5;
public static final int HEXAGON_MIDDLE_MIDDLE_APPEARANCE_POSITION = 6;
public static final int HEXAGON_MIDDLE_RIGHT_APPEARANCE_POSITION = 2;
public static final int HEXAGON_LOWER_RIGHT_APPEARANCE_POSITION = 3;
public static final int HEXAGON_LOWER_LEFT_APPEARANCE_POSITION = 4;
/**
 * Increase this for a slower animation i.e. decrease this for a faster animation.
 */
public static final int APPEARANCE_SPEED_COEFFICIENT = 10;

/**
 * The radius of each hexagon.
 */
private float mRadius;

/**
 * The width and height of each hexagon.
 */
private float mWidth, mHeight;

/**
 * The various hexagons as {@link Path} objects.
 */
private Path mHexagonUpperRight;
private Path mHexagonMiddleRight;
private Path mHexagonLowerRight;
private Path mHexagonLowerLeft;
private Path mHexagonMiddleLeft;
private Path mHexagonUpperLeft;
private Path mHexagonMiddleMiddle;

/**
 * The {@link Paint} objects for each hexagon. Every hexagon can have its own colour.
 */
private Paint mHexagonPaintUpperRight = new Paint();
private Paint mHexagonPaintMiddleRight = new Paint();
private Paint mHexagonPaintLowerRight = new Paint();
private Paint mHexagonPaintLowerLeft = new Paint();
private Paint mHexagonPaintMiddleLeft = new Paint();
private Paint mHexagonPaintUpperLeft = new Paint();
private Paint mHexagonPaintMiddleMiddle = new Paint();

/**
 * Field for identifying if hexagons should be currently set to the background colour or to
 * their given colour.
 */
private boolean displayHexagons = true;

private float mRadiusStep;
private float[] mHexagonRadius;

public HexagonLoadingView(Context context) {
    super(context);
}

public HexagonLoadingView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public HexagonLoadingView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

/**
 * Method for calculating the hexagons, taking into account the current radius of the specified
 * hexagon.
 */
private void calculateHexagons() {
    mHexagonPaintUpperRight.setShader(new LinearGradient(0, 0, 0, getHeight(),
            getContext().getResources().getColor(R.color.hex_loading_color_8),
            getContext().getResources().getColor(R.color.hex_loading_color_9),
            Shader.TileMode.MIRROR));
    mHexagonPaintMiddleRight.setShader(new LinearGradient(0, 0, 0, getHeight(),
            getContext().getResources().getColor(R.color.hex_loading_color_8),
            getContext().getResources().getColor(R.color.hex_loading_color_9),
            Shader.TileMode.MIRROR));
    mHexagonPaintLowerRight.setShader(new LinearGradient(0, 0, 0, getHeight(),
            getContext().getResources().getColor(R.color.hex_loading_color_8),
            getContext().getResources().getColor(R.color.hex_loading_color_9),
            Shader.TileMode.MIRROR));
    mHexagonPaintLowerLeft.setShader(new LinearGradient(0, 0, 0, getHeight(),
            getContext().getResources().getColor(R.color.hex_loading_color_8),
            getContext().getResources().getColor(R.color.hex_loading_color_9),
            Shader.TileMode.MIRROR));
    mHexagonPaintMiddleLeft.setShader(new LinearGradient(0, 0, 0, getHeight(),
            getContext().getResources().getColor(R.color.hex_loading_color_8),
            getContext().getResources().getColor(R.color.hex_loading_color_9),
            Shader.TileMode.MIRROR));
    mHexagonPaintUpperLeft.setShader(new LinearGradient(0, 0, 0, getHeight(),
            getContext().getResources().getColor(R.color.hex_loading_color_8),
            getContext().getResources().getColor(R.color.hex_loading_color_9),
            Shader.TileMode.MIRROR));
    mHexagonPaintMiddleMiddle.setShader(new LinearGradient(0, 0, 0, getHeight(),
            getContext().getResources().getColor(R.color.hex_loading_color_8),
            getContext().getResources().getColor(R.color.hex_loading_color_9),
            Shader.TileMode.MIRROR));

    mHexagonUpperLeft = calculatePath((int) -(mRadius), (int) -(mRadius * 1.7),
            mHexagonRadius[HEXAGON_UPPER_LEFT_APPEARANCE_POSITION]);
    mHexagonUpperRight = calculatePath((int) (mRadius), ((int) -(mRadius * 1.7)),
            mHexagonRadius[HEXAGON_UPPER_RIGHT_APPEARANCE_POSITION]);
    mHexagonMiddleLeft = calculatePath((int) (-1.95 * mRadius), 0,
            mHexagonRadius[HEXAGON_MIDDLE_LEFT_APPEARANCE_POSITION]);
    mHexagonMiddleMiddle = calculatePath(0, 0,
            mHexagonRadius[HEXAGON_MIDDLE_MIDDLE_APPEARANCE_POSITION]);
    mHexagonMiddleRight = calculatePath((int) (1.95 * mRadius), 0,
            mHexagonRadius[HEXAGON_MIDDLE_RIGHT_APPEARANCE_POSITION]);
    mHexagonLowerLeft = calculatePath((int) -(mRadius), (int) (mRadius * 1.7),
            mHexagonRadius[HEXAGON_LOWER_LEFT_APPEARANCE_POSITION]);
    mHexagonLowerRight = calculatePath((int) (mRadius), (int) (mRadius * 1.7),
            mHexagonRadius[HEXAGON_LOWER_RIGHT_APPEARANCE_POSITION]);
}

@Override
public void onDraw(Canvas c) {
    //Check if this is the first load, if so don't do anything and display only the background
    //for a while
    calculateHexagons();

    //Count the hexagons up i.e. down i.e. make them appear or disappear.
    //Increase always only one hexagon at a time which has not been fully drawn yet.
    //Also check which hexagons have been completed.
    int completedHexagons = 0;
    if (displayHexagons) {
        for (int i = 0; i < mHexagonRadius.length; i++) {
            if (mHexagonRadius[i] < mRadius) {
                mHexagonRadius[i] += mRadiusStep;
                break;
            }
            completedHexagons++;
        }
    } else {
        for (int i = 0; i < mHexagonRadius.length; i++) {
            if (mHexagonRadius[i] > 0) {
                mHexagonRadius[i] = (mHexagonRadius[i] + (mRadiusStep * -1) < 0) ? 0
                        : mHexagonRadius[i] + (mRadiusStep * -1);
                break;
            }
            completedHexagons++;
        }
    }

    checkDrawingMode(completedHexagons);

    //Now draw our hexagons
    c.drawPath(mHexagonUpperLeft, mHexagonPaintUpperLeft);
    c.drawPath(mHexagonUpperRight, mHexagonPaintUpperRight);
    c.drawPath(mHexagonMiddleRight, mHexagonPaintMiddleRight);
    c.drawPath(mHexagonLowerRight, mHexagonPaintLowerRight);
    c.drawPath(mHexagonLowerLeft, mHexagonPaintLowerLeft);
    c.drawPath(mHexagonMiddleLeft, mHexagonPaintMiddleLeft);
    c.drawPath(mHexagonMiddleMiddle, mHexagonPaintMiddleMiddle);
}

/**
 * Method for checking how many hexagons are completed in their drawing. If all hexagons are
 * completed (i.e. all appeared or disappeared), invert the drawing mode to the opposite of what
 * it was.
 */
private void checkDrawingMode(int completedHexagons) {
    if (completedHexagons == NUMBER_OF_HEXAGONS) {
        displayHexagons = !displayHexagons;
    }
}

@Override
protected void onAttachedToWindow() {
    super.onAttachedToWindow();

    mHexagonRadius = new float[NUMBER_OF_HEXAGONS];
    mHexagonRadius[HEXAGON_UPPER_LEFT_APPEARANCE_POSITION] = 0;
    mHexagonRadius[HEXAGON_UPPER_RIGHT_APPEARANCE_POSITION] = 0;
    mHexagonRadius[HEXAGON_MIDDLE_RIGHT_APPEARANCE_POSITION] = 0;
    mHexagonRadius[HEXAGON_LOWER_RIGHT_APPEARANCE_POSITION] = 0;
    mHexagonRadius[HEXAGON_LOWER_LEFT_APPEARANCE_POSITION] = 0;
    mHexagonRadius[HEXAGON_MIDDLE_LEFT_APPEARANCE_POSITION] = 0;
    mHexagonRadius[HEXAGON_MIDDLE_MIDDLE_APPEARANCE_POSITION] = 0;
}

@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    mWidth = MeasureSpec.getSize(widthMeasureSpec);
    mHeight = MeasureSpec.getSize(heightMeasureSpec);
    mRadius = mHeight / 6;
    mRadiusStep = mRadius / APPEARANCE_SPEED_COEFFICIENT;
}


/**
 * Calculate the path for a hexagon.
 *
 * @param xCenterScale The offset in the x direction.
 * @param yCenterScale The offset in the y direction.
 * @return The calculated hexagon as {@link Path} object.
 */
private Path calculatePath(int xCenterScale, int yCenterScale, float radius) {
    float triangleHeight = (float) (Math.sqrt(3) * radius / 2);
    float centerX = (mWidth / 2) + xCenterScale;
    float centerY = (mHeight / 2) + yCenterScale;
    Path hexagonPath = new Path();

    hexagonPath.moveTo(centerX, centerY + radius);
    hexagonPath.lineTo(centerX - triangleHeight, centerY + radius / 2);
    hexagonPath.lineTo(centerX - triangleHeight, centerY - radius / 2);
    hexagonPath.lineTo(centerX, centerY - radius);
    hexagonPath.lineTo(centerX + triangleHeight, centerY - radius / 2);
    hexagonPath.lineTo(centerX + triangleHeight, centerY + radius / 2);
    hexagonPath.moveTo(centerX, centerY + radius);

    invalidate();

    return hexagonPath;
  }


} 

如何将动画修改为完全像这样:https://codepen.io/wuser/pen/BgPMqE

最佳答案

首先,在 onDraw 方法中计算每个六边形对于图形性能来说非常昂贵,因为它为每个六边形创建一个着色器,它会因为 GC 而阻塞主线程。您可以在 onSizeChanged 回调中计算六边形。然后你可以使用 Canvas 的方法绘制每个六边形:canvas.translate()canvas.scale()。每个六边形的平移和缩放是根据动画师耗时计算的。对于这样的动画案例,您可以使用 TimerAnimator。在 View 中启动 TimerAnimator 后,它会每 16 毫秒调用一次回调。在此回调中,您可以为您的 View 调用 invalidate()。为了计算每个六边形的 alpha 值,您还应该使用耗时。对于这个 View ,只有一个 Paint 就足够了。另外,当 View 变为不可见或消失状态时,不要忘记停止 TimerAnimator。

关于android - 向 HexagonLoadingView 添加淡入淡出动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56900488/

有关android - 向 HexagonLoadingView 添加淡入淡出动画的更多相关文章

  1. ruby - 我需要将 Bundler 本身添加到 Gemfile 中吗? - 2

    当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/

  2. ruby - 将 Bootstrap Less 添加到 Sinatra - 2

    我有一个ModularSinatra应用程序,我正在尝试将Bootstrap添加到应用程序中。get'/bootstrap/application.css'doless:"bootstrap/bootstrap"end我在views/bootstrap中有所有less文件,包括bootstrap.less。我收到这个错误:Less::ParseErrorat/bootstrap/application.css'reset.less'wasn'tfound.Bootstrap.less的第一行是://CSSReset@import"reset.less";我尝试了所有不同的路径格式,但它

  3. ruby - 续集在添加关联时访问many_to_many连接表 - 2

    我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以

  4. ruby - 可以通过多少种方法将方法添加到 ruby​​ 对象? - 2

    当谈到运行时自省(introspection)和动态代码生成时,我认为ruby​​没有任何竞争对手,可能除了一些lisp方言。前几天,我正在做一些代码练习来探索ruby​​的动态功能,我开始想知道如何向现有对象添加方法。以下是我能想到的3种方法:obj=Object.new#addamethoddirectlydefobj.new_method...end#addamethodindirectlywiththesingletonclassclass这只是冰山一角,因为我还没有探索instance_eval、module_eval和define_method的各种组合。是否有在线/离线资

  5. ruby - 如何在 Ruby 中向现有方法定义添加语句 - 2

    我注意到类定义,如果我打开classMyClass,并在不覆盖的情况下添加一些东西我仍然得到了之前定义的原始方法。添加的新语句扩充了现有语句。但是对于方法定义,我仍然想要与类定义相同的行为,但是当我打开defmy_method时似乎,def中的现有语句和end被覆盖了,我需要重写一遍。那么有什么方法可以使方法定义的行为与定义相同,类似于super,但不一定是子类? 最佳答案 我想您正在寻找alias_method:classAalias_method:old_func,:funcdeffuncold_func#similartoca

  6. ruby-on-rails - 添加回形针新样式不影响旧上传的图像 - 2

    我有带有Logo图像的公司模型has_attached_file:logo我用他们的Logo创建了许多公司。现在,我需要添加新样式has_attached_file:logo,:styles=>{:small=>"30x15>",:medium=>"155x85>"}我是否应该重新上传所有旧数据以重新生成新样式?我不这么认为……或者有什么rake任务可以重新生成样式吗? 最佳答案 参见Thumbnail-Generation.如果rake任务不适合你,你应该能够在控制台中使用一个片段来调用重新处理!关于相关公司

  7. ruby - 我如何添加二进制数据来遏制 POST - 2

    我正在尝试使用Curbgem执行以下POST以解析云curl-XPOST\-H"X-Parse-Application-Id:PARSE_APP_ID"\-H"X-Parse-REST-API-Key:PARSE_API_KEY"\-H"Content-Type:image/jpeg"\--data-binary'@myPicture.jpg'\https://api.parse.com/1/files/pic.jpg用这个:curl=Curl::Easy.new("https://api.parse.com/1/files/lion.jpg")curl.multipart_form_

  8. Unity 3D 制作开关门动画,旋转门制作,推拉门制作,门把手动画制作 - 2

    Unity自动旋转动画1.开门需要门把手先动,门再动2.关门需要门先动,门把手再动3.中途播放过程中不可以再次进行操作觉得太复杂?查看我的文章开关门简易进阶版效果:如果这个门可以直接打开的话,就不需要放置"门把手"如果门把手还有钥匙需要旋转,那就可以把钥匙放在门把手的"门把手",理论上是可以无限套娃的可调整参数有:角度,反向,轴向,速度运行时点击Test进行测试自己写的代码比较垃圾,命名与结构比较拉,高手轻点喷,新手有类似的需求可以拿去做参考上代码usingSystem.Collections;usingSystem.Collections.Generic;usingUnityEngine;u

  9. 安卓apk修改(Android反编译apk) - 2

    最近因为项目需要,需要将Android手机系统自带的某个系统软件反编译并更改里面某个资源,并重新打包,签名生成新的自定义的apk,下面我来介绍一下我的实现过程。APK修改,分为以下几步:反编译解包,修改,重打包,修改签名等步骤。安卓apk修改准备工作1.系统配置好JavaJDK环境变量2.需要root权限的手机(针对系统自带apk,其他软件免root)3.Auto-Sign签名工具4.apktool工具安卓apk修改开始反编译本文拿Android系统里面的Settings.apk做demo,具体如何将apk获取出来在此就不过多介绍了,直接进入主题:按键win+R输入cmd,打开命令窗口,并将路

  10. ruby-on-rails - 在 Ruby on Rails 中添加 boolean 列值 - 2

    我正在开发一个创建网络博客的RubyonRails项目。我希望将一个名为featured的boolean数据库字段添加到Post模型中。该字段应该可以通过我添加的事件管理界面进行编辑。我使用了以下代码,但我什至没有在网站上显示另一列。$railsgeneratemigrationaddFeaturedfeatured:boolean$rakedb:migrate我是RubyonRails的新手,非常感谢任何帮助。我的index.html.erb文件中的相关代码(views):FeaturedPost架构.rb:ActiveRecord::Schema.define(:version=>

随机推荐