Andiamo per ordine: sarei contento se rifacessi la procedura di ImagePicker di sana pianta.
Sì, ma ho serie difficoltà per coniugare scaling e traslazione.
Bene, devi solo rivedere quelle due parole chiave del multitouch, allora. Ma prima io ricomincerei con un po' di sano esercizio sulla traslazione e lo scaling separati, giusto per rinfrescare la memoria.
Okay!
Traslazione:
Immagine:
public class Immagine extends View{
float lastX,lastY;
float posX, posY;
Drawable mImage;
Context context;
public Immagine(Context context) {
super(context);
this.context=context;
mImage=getResources().getDrawable(R.drawable.facciadaculo);
mImage.setBounds(0,0,mImage.getIntrinsicWidth(),mImage.getIntrinsicHeight());
}
@Override
public boolean onTouchEvent(MotionEvent event){
int action=event.getAction() & MotionEvent.ACTION_MASK;
switch(action){
case MotionEvent.ACTION_DOWN:
lastX=event.getX();
lastY=event.getY();
break;
case MotionEvent.ACTION_MOVE:
posX+=event.getX()-lastX;
posY+=event.getY()-lastY;
invalidate();
lastX=event.getX();
lastY=event.getY();
break;
}
return true;
}
@Override
public void onDraw(Canvas canvas){
super.onDraw(canvas);
canvas.save();
canvas.translate(posX, posY);
mImage.draw(canvas);
canvas.restore();
}
}
MainLayout:
public class MainActivity extends AppCompatActivity {
Immagine immagine;
RelativeLayout mainLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainLayout=(RelativeLayout)findViewById(R.id.mainLayout);
immagine=new Immagine(this);
mainLayout.addView(immagine);
RelativeLayout.LayoutParams params=(RelativeLayout.LayoutParams)immagine.getLayoutParams();
params.width=300;
params.height=300;
}
}
E funziona!
Esercizio di scaling:
public class Immagine extends View{
float scaleFactor=1.f;
ScaleGestureDetector mDetector;
Drawable mImage;
Context context;
public Immagine(Context context) {
super(context);
this.context=context;
mImage=getResources().getDrawable(R.drawable.facciadaculo);
mImage.setBounds(0,0,mImage.getIntrinsicWidth(),mImage.getIntrinsicHeight());
mDetector=new ScaleGestureDetector(context,new ScaleDetector());
}
@Override
public boolean onTouchEvent(MotionEvent event){
mDetector.onTouchEvent(event);
return true;
}
@Override
public void onDraw(Canvas canvas){
super.onDraw(canvas);
canvas.save();
canvas.scale(scaleFactor,scaleFactor);
mImage.draw(canvas);
canvas.restore();
}
class ScaleDetector extends ScaleGestureDetector.SimpleOnScaleGestureListener{
@Override
public boolean onScale(ScaleGestureDetector detector){
scaleFactor*=detector.getScaleFactor();
invalidate();
return true;
}
}
}
Perfetto! (MainActivity è sempre uguale).
Nessun commento:
Posta un commento