所以,我想更新一个
我想设置一个径向渐变,其中心在单击事件处。我首先尝试根据这个想法设置布局背景,一切都很顺利。然后我尝试将其更改为布局中所需的可视元素大小和位置的
以下是代码:
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);
}
这里有一张图片展示了我得到的结果,我用红圈标出了光标的位置。错位的渐变