Android 9(API 级别 28)及更高版本中提供放大镜微件,放大镜可放大模糊或缩小的视图。导入android.widget.Magnifier类,利用auto.js写一个视图放大镜的脚本。两种方法,一种是简易的直接创建Magnifier类,另一种自定义放大镜通过Magnifier.Builder创建。
演示:
一.简易放大镜
安卓开发文档:
https://developer.android.google.cn/reference/android/widget/Magnifier?hl=zh
"ui";
/**
* 作者: 姜来式
* QQ: 1216951671
*/
importClass("android.widget.Magnifier")
ui.layout(
<vertical id="a" gravity="center">
<TextView marginTop="50" w="auto" h="auto" text='日照香炉生紫烟,遥看瀑布挂前川。' textSize="20sp" />
<TextView w="auto" h="auto" text='飞流直下三千尺,疑是银河落九天。' textSize="20sp"/>
<img src="file://./logo.png"/>
</vertical>);
magnifier = new Magnifier(ui.a);
ui.a.setOnTouchListener(function(view, event) {
switch (event.getAction()) {
case event.ACTION_MOVE:
x = event.getRawX();//触摸屏幕的坐标
y = event.getRawY();
magnifier.setZoom(1.2) //放大倍数
magnifier.show(x,y-100)//放大镜显示位置
return true;
case event.ACTION_UP:
magnifier.dismiss()//关闭放大镜
return true;
}
return true;
});
//show(float sourceCenterX, float sourceCenterY) Shows the magnifier on the screen
//setZoom(float zoom) Sets the zoom to be applied to the chosen content before being copied to the magnifier popup.
//dismiss() Dismisses the magnifier from the screen
在测试的时候,出现视图的getHeight()和getWidth()返回值为0的情况,原因在于过早的调用这些方法,等到View绘制完成后才可以成功获取到尺寸。
二.Builder自定义放大镜
安卓开发文档:
https://developer.android.google.cn/reference/android/widget/Magnifier.Builder?hl=zh
* QQ: 1216951671
*/
importClass("android.widget.Magnifier")
ui.layout(
<vertical id="a" gravity="center">
<TextView marginTop="50" w="auto" h="auto" text='日照香炉生紫烟,遥看瀑布挂前川。' textSize="20sp" textIsSelectable ="true"/>
<TextView w="auto" h="auto" text='飞流直下三千尺,疑是银河落九天。' textSize="20sp"/>
<img src="file://./logo.png"/>
</vertical>);
builder = new Magnifier.Builder(ui.a)
magnifier2=builder.setClippingEnabled(true)//可复制
.setCornerRadius(80)//圆角
.setSize(600,200)//放大镜显示大小
.build()
ui.a.setOnTouchListener(function(view, event) {
switch (event.getAction()) {
case event.ACTION_MOVE:
x = event.getRawX();
y = event.getRawY();
magnifier2.show(x,y-100)
return true;
case event.ACTION_UP:
magnifier2.dismiss()
return true;
}
return true;
});
//setClippingEnabled(boolean clip) Defines the behavior of the magnifier when it is requested to position outside the surface of the main application window.
//setCornerRadius(float cornerRadius)Sets the corner radius of the magnifier window, in pixels.
//setSize(int width, int height)Sets the size of the magnifier window, in pixels.
//build() Builds a Magnifier instance based on the configuration of this Builder.