所以,我不想更新ImageView
来根据手机陀螺仪和光传感器的一些事件来改变梯度。然而,此刻我正在尝试点击事件。
我想设置一个以单击事件为中心的径向渐变。我第一次尝试设置布局背景时考虑到了这一点,一切都很好。然后,我尝试将其更改为布局中的ImageView
(在大小和位置上是所需的视觉元素),梯度中心向下向右移动。
这是代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_seeker);
RelativeLayout layout = (RelativeLayout) findViewById(R.id.seeker_layout);
layout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
int location[] = new int[2];
//measuring location of Image View to try and find correlation to shift
findViewById(R.id.gradient_indicator).getLocationOnScreen(location);
int grad_height = findViewById(R.id.gradient_indicator).getMeasuredHeight();
int grad_width = findViewById(R.id.gradient_indicator).getMeasuredWidth();
final float pos_x = event.getX();
final float pos_y = event.getY();
Toast position = Toast.makeText(getApplicationContext(), "Event Position (" + String.valueOf(pos_x) + "x" + String.valueOf(pos_y) + ")n Window Dimensions(" + grad_width + "x" + grad_height + ")n Window Position(" + location[0] + "x" + location[1] + ")", Toast.LENGTH_LONG);
position.show();
ShapeDrawable.ShaderFactory shader_factory = new ShapeDrawable.ShaderFactory() {
@Override
public Shader resize(int width, int height) {
RadialGradient radialGradient = new RadialGradient(pos_x, pos_y, 350, 0xff0000ff, 0, Shader.TileMode.MIRROR);
return radialGradient;
}
};
//Set curve radius to equal values in dp as specified in loaded xml shape
float dp_radius = 5;
int curve = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,dp_radius, getResources().getDisplayMetrics());
float[] r_radii = new float[8];
Arrays.fill(r_radii,curve);
//create shape programatically that matches xml one
RoundRectShape rs = new RoundRectShape(r_radii, null, null);
ShapeDrawable sd = new ShapeDrawable(rs);
sd.setShaderFactory(shader_factory);
ImageView gradient_indicator = (ImageView) findViewById(R.id.gradient_indicator);
if (Build.VERSION.SDK_INT >= 15) {
setBackgroundV15Plus(gradient_indicator, sd);
} else {
setBackgroundV15Minus(gradient_indicator, sd);
}
}
return true;
}
});
}
@TargetApi(15)
private void setBackgroundV15Plus(View view, ShapeDrawable sd) {
view.setBackground(sd);
}
@SuppressWarnings("deprecation")
private void setBackgroundV15Minus(View view, ShapeDrawable sd) {
view.setBackgroundDrawable(sd);
}
这是我得到的结果的图像,我用红圈标记了光标的位置。位移梯度
Nanoc建议的工作解决方案(它不是超级优雅,但它很有效):
我计算它的方法是在xml ImageView声明中添加边距。然后,您可以从Java访问边距,而无需转换dp像素单位。从事件位置中减去所有
访问边距的代码:
ImageView gradient_indicator=(ImageView)findViewById(R.id.gradient_indicator);RelativeLayout.LayoutParams lp=(RelativeLLayout.LayoutParams)gradient_indicator.getLayoutParams();int grad_margin_top=lp.topMargin;int grad_margin_left=lp.leftMargin;