2013-09-02 107 views
5

Tôi đang cố gắng sử dụng thư viện PhotoView để tạo công cụ cắt ảnh nhưng tôi không hiểu được giá trị được trả lại bởi getDisplayRect(). Tôi đặt ảnh trên ImageView như vậy:Tôi gặp khó khăn khi hiểu getDisplayRect() của PhotoView thực sự trả về (xây dựng công cụ cắt ảnh android)

photo.setImageDrawable(new BitmapDrawable(getResources(), image)); 

nơi image là đối tượng Bitmap. Sau đó tôi thiết lập một số giá trị chia tỷ lệ:

float minScale = ((float)image.getWidth() > (float)image.getHeight()) 
    ? (float)image.getWidth()/(float)image.getHeight() 
    : (float)image.getHeight()/(float)image.getWidth(); 
attacher.setMaxScale(minScale * 5f); 
attacher.setMidScale(minScale * 2.5f); 
attacher.setMinScale(minScale); 
attacher.setScale(minScale, (float)image.getWidth()/2f,(float)image.getHeight()/2f, false); 
attacher.update(); 

nơi attacher là đối tượng PhotoViewAttacher.

Khi người dùng được thực hiện tôi sử dụng những điều sau đây để xác định phần Bitmap đó là được nhìn thấy trong ImageView:

RectF rect  = attacher.getDisplayRect(); 
float scale    = attacher.getScale(); 
PhotoData ret = new PhotoData(data); 
ret.x  = (int)(Math.abs(rect.left)/scale); 
ret.y  = (int)(Math.abs(rect.top)/scale); 
ret.width = (int)(rect.width()/scale); 
ret.height = (int)(rect.height()/scale); 

tôi nhận được kết quả bất ngờ mặc dù. Có lẽ ai đó ở đây có thể cung cấp một số thông tin chi tiết?

Trả lời

6

Dưới đây là câu trả lời:

  RectF rect   = attacher.getDisplayRect(); 
      float viewScale  = attacher.getScale(); 

      float imageRatio = (float)size.width()/(float)size.height(); 
      float viewRatio = (float)photoView.getWidth()/(float)photoView.getHeight(); 

      float scale = 0; 
      if (imageRatio > viewRatio) { 
       // scale is based on image width 
       scale = 1/((float)size.width()/(float)photoView.getWidth()/viewScale); 

      } else { 
       // scale is based on image height, or 1 
       scale = 1/((float)size.height()/(float)photoView.getHeight()/viewScale); 
      } 

      // translate to bitmap scale 
      rect.left  = -rect.left/scale; 
      rect.top  = -rect.top/scale; 
      rect.right  = rect.left + ((float)photoView.getWidth()/scale); 
      rect.bottom  = rect.top + ((float)photoView.getHeight()/scale); 

      if (rect.top<0) { 
       rect.bottom -= Math.abs(rect.top); 
       rect.top = 0; 
      } 
      if (rect.left<0) { 
       rect.right -= Math.abs(rect.left); 
       rect.left = 0; 
      } 
+0

là gì size.width() và size.height()? – braintrapp

+0

@ user3809445 Tôi đoán biến kích thước đề cập đến Bitmap của tệp hình ảnh gốc được hiển thị trong PhotoView. – AmuletxHeart