2015-02-02 2 views
-1

Я знаю, что если у меня есть фоновое изображение, независимо от того, насколько оно велико, и я установил корневую компоновку (скажем, linearlayout), чтобы иметь это изображение в качестве фона, тогда оно сделано чтобы соответствовать экрану.Установите фон макета на часть изображения

Теперь мой вопрос, есть ли способ установить фон макета на часть изображения (чтобы, если я кастую, используя жест, я могу просматривать другие части фонового изображения)?

Большое спасибо

+0

Почему бы вам разделить ваш макет на две? Показать/скрыть одну половину по клавиатуре? – Skynet

+0

Это не ограничивается двумя. Я хочу установить фон в часть изображения в зависимости от того, где пользователь (подумайте об этом, как о стратегической игре или экшн-игре, где у вас есть карта, и вы перемещаетесь) – Snake

+0

Вам придется рисовать каждый элемент фона отдельно Я думаю. – Skynet

ответ

0
you have to make two image put it in framelayout use this code this color code match class 


public class ColorTool { 
public boolean closeMatch (int color1, int color2, int tolerance) { 
    if ((int) Math.abs (Color.red (color1) - Color.red (color2)) > tolerance) return false; 
    if ((int) Math.abs (Color.green (color1) - Color.green (color2)) > tolerance) return false; 
    if ((int) Math.abs (Color.blue (color1) - Color.blue (color2)) > tolerance) return false; 

    return true; 
} // end match 

} 

get background color of background image by this method 

public int getHotspotColor(int hotspotId, int x, int y) { 
     ImageView img = (ImageView) findViewById(hotspotId); 
     if (img == null) { 
      Log.d("ImageAreasActivity", " Hot spot image not found"); 
      return 0; 
     } else { 
      img.setDrawingCacheEnabled(true); 
      Bitmap hotspots = Bitmap.createBitmap(img.getDrawingCache()); 
      if (hotspots == null) { 
       Log.d("ImageAreasActivity", "Hot spot bitmap was not created"); 
       return 0; 
      } else { 
       img.setDrawingCacheEnabled(false); 
       return hotspots.getPixel(x, y); 
      } 
     } 
    } 
set ontouchlistener on that image and implement ontouch method like this 


public boolean onTouch(View v, MotionEvent ev) { 
     boolean handledHere = false; 
     final int action = ev.getAction(); 
     final int evX = (int) ev.getX(); 
     final int evY = (int) ev.getY(); 
     int nextImage = -1; 

     ImageView imageView = (ImageView) v.findViewById(R.id.image); 
     if (imageView == null) 
      return false; 

     Integer tagNum = (Integer) imageView.getTag(); 
     int currentResource = (tagNum == null) ? R.drawable.backgroundimage 
       : tagNum.intValue(); 
     switch (action) { 
     case MotionEvent.ACTION_DOWN: 
      if (currentResource == R.drawable.backgroundimage) { 
       nextImage = R.drawable.setimage; 
       handledHere = true; 
      } else 
       handledHere = true; 
      break; 

     case MotionEvent.ACTION_UP: 

      int touchColor = getHotspotColor(R.id.image_areas, evX, evY); 
      ColorTool ct = new ColorTool(); 
      int tolerance = 25; 
      nextImage = R.drawable.backgroundimage; 
       if (ct.closeMatch(Color.RED, touchColor, tolerance)) 
       nextImage = 0; 
      else if (ct.closeMatch(Color.GREEN, touchColor, tolerance)) 
       nextImage = 1; 
      else if (ct.closeMatch(Color.BLUE, touchColor, tolerance)) 
       nextImage = 2; 
      else if (ct.closeMatch(Color.WHITE, touchColor, tolerance)) 
       nextImage = 3; 
      if (currentResource == nextImage) { 

       nextImage = -1; 
      } 
         handledHere = true; 
      break; 

     default: 
      handledHere = false; 
     } // end switch 

     if (handledHere) { 

      if (nextImage == 0) { 

       /* put your code of setbackground image here for first matching color code */ 
      } 
      if (nextImage == 1) { 
      /* put your code of setbackground image here for second matching color code */ 
       iv.setOnTouchListener(null); 
      } 
      if (nextImage == 2) { 

       /* put your code of setbackground image here for third matching color code */ 
       iv.setOnTouchListener(null); 
      } 
      if (nextImage == 3) { 

      } 
     } 
     return handledHere; 
    } 


layout 

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/my_frame" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" > 

    <ImageView 
     android:id="@+id/image_areas" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:scaleType="fitXY" 
     android:src="@drawable/homeback2" 
     android:visibility="invisible"/> 
    <ImageView 
     android:id="@+id/image" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:scaleType="fitXY" 
     android:src="@drawable/homefront2"/> 
      <!-- android:scaleType="centerCrop" --> 
</FrameLayout> 
+0

Спасибо, это немного близко к тому, что я хочу. Но не совсем. подумайте об этом, как о стратегической игре или экшн-игре, где у вас есть карта, и вы двигаетесь. Таким образом, вы показываете новые/разные части изображения. Это то, что я хочу. Я хочу установить фон для определенной области изображения в зависимости от времени. Я соглашусь, что ваш ответ будет самым близким, хотя, если вы не можете дать лучший ответ (тогда я тоже его рассмотрю) – Snake

0

поставить эту строку в XML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     android:id="@+id/li"  
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     /* this line is for setting background image */ 
     android:background="@drawable/Image" 
     android:orientation="vertical" > 

и если вы хотите изменить изображение с помощью кода поместить эту строку

  linearlayout=(LinearLayout)findViewById(R.id.li); 
      linearlayout.setBackgroundResource(R.drawable.logo); 
+0

Я не спрашиваю, как установить фон для изображения. Я спрашиваю, как установить фон на часть изображения. – Snake

+0

вам нужно сделать два изображения положить его в framelayout использовать этот код –

Смежные вопросы