在android中定义缩放图像上的可触摸区域
问题描述:
我之前已经提出过与此相关的问题,但我认为我错误地构思了我的目标。在android中定义缩放图像上的可触摸区域
我拥有的:一个自定义的ImageView,它显示图形并将多个可触摸区域定义为图像中的矩形。我的问题是缩放。我想根据位图文件中的实际分辨率来定义图像的可触摸区域,但要翻译这些坐标,以便矩形覆盖缩放图像上的相同区域。
这是我到目前为止有: 当创建视图,计算实际的比例缩放大小
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
Drawable pic=this.getDrawable();
int realHeight= pic.getIntrinsicHeight();
int realWidth=pic.getIntrinsicWidth();
int scaledHeight=this.getHeight();
int scaleWidth=this.getWidth();
heightRatio=(float)realHeight/scaledHeight;
widthRatio=(float)realWidth/scaleWidth;
}
现在,我想借此定义矩形的坐标(s)原始(未缩放)图像 和绘制矩形(县)的图像在同一地区 - 但占规模:
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint p=new Paint();
p.setStrokeWidth(1);
p.setColor(Color.BLUE);
for (HotSpot h: spots)
{
//Each hotspot has a rectangle defined in reference to the actual size of the image
Rect old=h.getRect();
float offsetLeft=old.left+(old.left*widthRatio);
float offsetTop=old.top+(old.top*heightRatio);
float offsetRight=old.right+(old.right*heightRatio);
float offsetBottom=old.bottom+(old.bottom*widthRatio);
RectF nRect=new RectF(offsetLeft,offsetTop,offsetRight,offsetBottom);
canvas.drawRect(nRect,p);
}
的结果是“在棒球场”,但不是很准确。任何帮助表示赞赏。
答
你可以试试这个解决方案:
- 获取屏幕密度
- 获取图像的高度(或宽度)
- 鸿沟的高度(或宽度)的密度,所以你得到的长度以英寸为单位
- 将坐标除以英寸的长度,所以你得到坐标和图像之间的关系,这是由图像独立的有效尺寸
- 当你必须绘制相同的点一个不同地缩放图像,乘最后的结果为长度在第二图像的英寸(你获得使用上面列出的相同的操作)
实施例: 在第一图像:
float density = getResources().getDisplayMetrics().density;
int width = getWidth();
float inchesLength = width/density;
float scaledXCenter = xCenter/inchesLength;
在不同比例的相同图像上:
float density = getResources().getDisplayMetrics().density;
int width = getWidth();
float inchesLength = width/density;
float restoredXCenter = scaledXCenter * inchesLength;