所以,我不想更新ImageView
根據手機陀螺儀和Lightsensor的一些事件來改變漸變。然而,在這一刻,我正在嘗試與點擊事件。安卓圖像視圖漸變背景
我想在click事件中設置一個帶有中心的徑向漸變。我首先嚐試着設置佈局背景,並且一切都很好。然後,我嘗試在佈局中更改它爲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);
}
而這裏的我得到的,我標誌着光標的紅色圓圈的位置的結果的圖像。 Displaced Gradient
如果它在用作佈局背景時工作,我會打賭,如果您使imageview全屏幕它應該工作,也許你需要從圖像視圖位置偏移x,y。在佈局背景中使用時,您是否注意到中心正在向底部移動? – Nanoc
問題的根源似乎是在xml中設置的邊距或填充。如果我在ImageView本身上設置了邊距,或者在保存圖像的相對視圖上進行了填充,它仍然存在。如果我把它帶到全屏,沒有問題。我可以通過減去實際點擊事件中的邊距像素來解決這個問題。不過,我希望這可以更優雅地解決,也許在調用Shader resize函數時。 –
如果你不想讓imageview全屏顯示,那麼這是唯一的方法,在IOS中你有一個bult-in函數可以將touchevent抵消給定的視圖,在Android中你必須手動完成。無論如何,所有你的問題是由不閱讀此:)引起的http://stackoverflow.com/questions/29956014/why-should-we-use-xml-layouts – Nanoc