【问题标题】:How to animate image to top right of screen如何将图像动画到屏幕右上角
【发布时间】:2018-07-05 03:51:16
【问题描述】:

我是安卓开发的新手。 我想在更改图像大小(更小)的同时将图像从中心移到屏幕右上角。

我尝试了以下方法-

  1. 对 translationX 和 translationY 进行硬编码,输入一个特定的值,例如 -150dp,这在我的模拟器屏幕上看起来不错,但不同设备上的图像位置不同。

  2. .getX 。 getY 方法,我尝试在我想要放置图像的位置放置一个不可见的图像(alpha 0),并设置图像的 getx 和 y 并设置平移 x,y 但它不起作用,图像从我的屏幕上滑出。

我想如果我能获得像 textview 这样的对象的位置并将图像位置设置为 objectposition+somevalue 会起作用但我不知道该怎么做。 有人可以帮我吗?

这是我正在尝试做的图像。 提前致谢。

【问题讨论】:

    标签: java android android-layout android-studio


    【解决方案1】:

    试试这个,希望这段代码对你有帮助

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
    
        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Your Text"
            android:layout_gravity="center"/>
    
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@android:drawable/star_big_off" />
    </LinearLayout>
    

    【讨论】:

    • 感谢您提供此代码 sn-p,它可能会提供一些有限的即时帮助。 proper explanation 将通过展示为什么这是解决问题的好方法,并使其对有其他类似问题的未来读者更有用,从而大大提高其长期价值。请edit您的回答添加一些解释,包括您所做的假设。
    【解决方案2】:

    尝试使用

      view.animate().x(dx).y(-dy)
    

    在文档中写到这些是绝对坐标,但实际上它变成了一个增量,我需要更改它。 X - 按左侧计算,Y - 顶部。
    对于获取坐标,您可以使用 rect:

     private fun getLocationOnScreen(view: View): Rect {
        val rect = Rect()
        view.getGlobalVisibleRect(rect)
        return rect
    }
    

    您还需要更改图片的大小。对他们来说,使用比例动画,但之前需要计算百分比。有些是这样的:

    val textRect = getLocationOnScreen(textView)
    val imageRect = getLocationOnScreen(imageView)
    val width = getWidth()//some method that get screen width on pxl
    val height = getHeight()
    val xScale = (width - textRect.right) / (imageRect.right - imageRect.left).toFlooat()
    val yScale = (height - textRect.bottom) / (imageRect.bottom - imageRect.top).toFloat()
    val scale = ScaleAnimation(
                1.0f, xScale ,
                1.0f, yScale ,
                Animation.RELATIVE_TO_SELF, pivotX, // optional
                Animation.RELATIVE_TO_SELF, pivotY //optional
    )
    scale.duration = 1000L
    imageView.startAnimation(scale)
    

    我希望有些东西会有所帮助,或者也许什么都不起作用 =)

    【讨论】:

      猜你喜欢
      • 2022-06-24
      • 1970-01-01
      • 1970-01-01
      • 2017-02-01
      • 2012-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-20
      相关资源
      最近更新 更多