2012-01-15 95 views
0

我之前已經提出過與此相關的問題,但我認爲我錯誤地構思了我的目標。在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); 

} 

的結果是「在棒球場」,但不是很準確。任何幫助表示讚賞。

回答

0

你可以試試這個解決方案:

  • 獲取屏幕密度
  • 獲取圖像的高度(或寬度)
  • 鴻溝的高度(或寬度)的密度,所以你得到的長度以英寸爲單位
  • 將座標除以英寸的長度,所以你得到座標和圖像之間的關係,這是由圖像獨立的有效尺寸
  • 當你必須繪製相同的點一個不同地縮放圖像,乘最後的結果爲長度在第二圖像的英寸(你獲得使用上面列出的相同的操作)

實施例: 在第一圖像:

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; 
相關問題