Android imageview get pixel color from scaled image

前端 未结 2 1125
醉酒成梦
醉酒成梦 2021-02-01 10:55

My home automation app has a feature where people can upload images to their phone with floorplans and dashboards that they can use to control their home automation software. I

相关标签:
2条回答
  • 2021-02-01 11:25

    After 7 years I have to provide another answer, because after upgrading to LG G8s from LG G6 the code from accepted answer stopped returning the correct color.

    This solution works on all the phones I found at home, but who knows... maybe even this one is not universal.

    (Using Xamarin C# but the principle is easy to understand)

    First we have to get the actual ImageView size as float to get floating point division

    private float imageSizeX;
    private float imageSizeY;
    
    private void OnCreate(...) {
        ...
        FindViewById<ImageView>(Resource.Id.colpick_Image).LayoutChange += OnImageLayout;
        FindViewById<ImageView>(Resource.Id.colpick_Image).Touch += Image_Touch;
        ...
    }
    
    //Event called every time the layout of our ImageView is updated
    private void OnImageLayout(object sender, View.LayoutChangeEventArgs e) {
        imageSizeX = Image.Width;
        imageSizeY = Image.Height;
        Image.LayoutChange -= OnImageLayout; //Just need it once then unsubscribe
    }
    
    //Called every time user touches/is touching the ImageView
    private void Image_Touch(object sender, View.TouchEventArgs e) {
        MotionEvent m = e.Event;
    
        ImageView img = sender as ImageView;
    
        int x = Convert.ToInt32(m.GetX(0));
        int y = Convert.ToInt32(m.GetY(0));
    
        Bitmap bmp = (img.Drawable as BitmapDrawable).Bitmap;
    
        // The scale value (how many times is the image bigger)
        // I only use it with images where Width == Height, so I get
        // scaleX == scaleY
        float scaleX = bmp.Width / imageSizeX;
        float scaleY = bmp.Height / imageSizeY;
    
        x = (int)(x * scaleX);
        y = (int)(y * scaleY);
    
        // Check for invalid values/outside of image bounds etc...
    
        // Get the correct Color ;)
        int color = bmp.GetPixel(x, y);
    }
    
    0 讨论(0)
  • 2021-02-01 11:29

    I figured it out. I replaced

     xCoord = Integer.valueOf((int)ev.getRawX());
     yCoord = Integer.valueOf((int)ev.getRawY());
    

    with

     Matrix inverse = new Matrix();
     v.getImageMatrix().invert(inverse);
     float[] touchPoint = new float[] {ev.getX(), ev.getY()};
     inverse.mapPoints(touchPoint);
     xCoord = Integer.valueOf((int)touchPoint[0]);
     yCoord = Integer.valueOf((int)touchPoint[1]);
    
    0 讨论(0)
提交回复
热议问题