我使用可在任何应用程序上看到的服务创建了叠加浮动图标。我已将其实施如下:http://www.piwai.info/chatheads-basics/
现在我想要的是当用户在任何方向上拖动此叠加图标时,应该从叠加图标的初始位置开始绘制矩形到新位置。我尝试使用canvas创建一个可调整大小的矩形并将其添加到windowmanager但是当它被添加到窗口时我无法调整它的大小。
简而言之,这就是我想要实现的目标:
1>用户按位置说出(x1,y1)
的叠加图标2>用户将叠加图标拖动到位置说(x2,y2)
3>当用户将叠加图标从(x1,y1)拖动到(x2,y2)时,会创建一个矩形。
这是我到目前为止所尝试的:
public class MyService extends Service
{
.....
public void onCreate()
{
super.onCreate();
floatingFaceBubble = new ImageView(this);
floatingFaceBubble.setImageResource(R.mipmap.ic_launcher);
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
final LayoutParams myParams = new WindowManager.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT,
LayoutParams.TYPE_PHONE,
LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
myParams.gravity = Gravity.TOP | Gravity.START;
myParams.x = 0;
myParams.y = 100;
windowManager.addView(floatingFaceBubble, myParams);
try
{
floatingFaceBubble.setOnTouchListener(new View.OnTouchListener()
{
private int initialX;
private int initialY;
private float initialTouchX;
private float initialTouchY;
private long touchStartTime = 0;
@Override
public boolean onTouch(View v, MotionEvent event)
{
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
touchStartTime = System.currentTimeMillis();
initialX = myParams.x;
initialY = myParams.y;
initialTouchX = event.getRawX();
initialTouchY = event.getRawY();
floatingFaceBubble.setVisibility(View.INVISIBLE);
rectangleview=new RectangleView(getApplicationContext(),initialTouchX,initialTouchY,event.getRawX(),event.getRawY());
windowManager.addView(rectangleview,myParams);
break;
case MotionEvent.ACTION_UP: //this case will be executed when button(image) is released
break;
case MotionEvent.ACTION_MOVE: //this case will be executed when button(image) is moved
floatingFaceBubble.setVisibility(View.VISIBLE);
myParams.x = initialX + (int) (event.getRawX() - initialTouchX);
myParams.y = initialY + (int) (event.getRawY() - initialTouchY);
windowManager.updateViewLayout(v, myParams);
break;}}}}}
这是我的Rectangleview:
public class RectangleView extends View
{
Paint paint = new Paint();
float pointX;
float pointY;
float startX;
float startY;
public RectangleView(Context context,float x1,float y1,float x2,float y2)
{
super(context);
paint.setStyle(Paint.Style.STROKE);
paint.setColor(Color.RED);
startX=x1;
startY=y1;
pointX=x2;
pointY=y2; }
@Override
public boolean onTouchEvent(MotionEvent event)
{
pointX = event.getX();
pointY = event.getY();
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
startX = pointX;
startY = pointY;
return true;
case MotionEvent.ACTION_MOVE:
pointX=event.getX();
pointY=event.getY();
break;
default:
return false;
}
// Force a view to draw again
postInvalidate();
return true;
}
@Override
public void onDraw(Canvas canvas)
{
canvas.drawRect(startX, startY, pointX, pointY,paint);
}
}