1. 程式人生 > >實現點擊圖片不同區域響應不同的事件

實現點擊圖片不同區域響應不同的事件

位置 轉換 unit 點擊 yun 單元 cgpoint use float

最近有一個遙控器的項目, 需要實現點擊圖片上指定位置響應不同事件

圖片如下:

技術分享

大概目的是點擊圖片上的溫度可以直接改變空調溫度

大概思路就是先通過gesture獲取點擊的點坐標, 然後對坐標做處理.

開始考慮以縱軸為0度, 計算點擊坐標跟中心點連線並計算跟縱軸的角度來判斷, 不過代碼寫好後發現在不同的設備上有誤差

所以就改用將圖片分成一個個的格子, 然後判斷觸摸點在哪一個格子上面

下面來說說做法:

首先把圖片放到一個表格中, 調增好表格的縮放大小剛好圖片邊緣壓在單元格線上

如圖:

技術分享

從這裏可看到, 將圖片分割成 高度: 43個單位 寬度: 9個單位

然後做個記錄每個點在哪些單元格上面:

我的記錄如下:

技術分享

然後我們可以寫代碼, 給ImageView添加一個手勢

   self.bgImg.userInteractionEnabled = YES;
    [self.bgImg addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tempTapAction:)]];

從gesture獲取轉換後的坐標並做判斷:

- (void)tempTapAction:(UIGestureRecognizer *)tapGesture {
    
    
float xunit = self.bgImg.frame.size.width / 9; float yunit = self.bgImg.frame.size.height / 43; CGPoint point; point = [tapGesture locationInView:self.bgImg]; // NSLog(@"點擊: %@", NSStringFromCGPoint(point)); if (point.x < xunit * 2 && (point.y > yunit * 27 && point.y < yunit * 31
)) { NSLog(@"16度"); _temper = 16; } else if (point.x < xunit * 2 && (point.y > yunit * 22 && point.y < yunit * 26)) { NSLog(@"17度"); _temper = 17; } else if (point.x < xunit * 2 && (point.y > yunit * 17 && point.y < yunit * 21)) { NSLog(@"18度"); _temper = 18; } else if (point.x < xunit * 2 && (point.y > yunit * 12 && point.y < yunit * 16)) { NSLog(@"19度"); _temper = 19; } else if ((point.x < xunit * 3 && point.x > xunit * 1) && (point.y > yunit * 8 && point.y < yunit * 12)) { NSLog(@"20度"); _temper = 20; } else if ((point.x < xunit * 3 && point.x > xunit * 2) && (point.y > yunit * 5 && point.y < yunit * 9)) { NSLog(@"21度"); _temper = 21; } else if ((point.x < xunit * 4 && point.x > xunit * 3) && (point.y > yunit * 3 && point.y < yunit * 7)) { NSLog(@"22度"); _temper = 22; } else if ((point.x < xunit * 5 && point.x > xunit * 4) && (point.y > yunit * 2 && point.y < yunit * 6)) { NSLog(@"23度"); _temper = 23; } else if ((point.x < xunit * 6 && point.x > xunit * 5) && (point.y > yunit * 3 && point.y < yunit * 7)) { NSLog(@"24度"); _temper = 24; } else if ((point.x < xunit * 7 && point.x > xunit * 6) && (point.y > yunit * 5 && point.y < yunit * 9)) { NSLog(@"25度"); _temper = 25; } else if ((point.x < xunit * 8 && point.x > xunit * 6) && (point.y > yunit * 8 && point.y < yunit * 12)) { NSLog(@"26度"); _temper = 26; } else if ((point.x < xunit * 9 && point.x > xunit * 7) && (point.y > yunit * 12 && point.y < yunit * 16)) { NSLog(@"27度"); _temper = 27; } else if ((point.x < xunit * 9 && point.x > xunit * 7) && (point.y > yunit * 17 && point.y < yunit * 21)) { NSLog(@"28度"); _temper = 28; } else if ((point.x < xunit * 9 && point.x > xunit * 8) && (point.y > yunit * 22 && point.y < yunit * 26)) { NSLog(@"29度"); _temper = 29; } else if ((point.x < xunit * 9 && point.x > xunit * 7) && (point.y > yunit * 27 && point.y < yunit * 31)) { NSLog(@"30度"); _temper = 30; } // 調用修改溫度方法 }

實現點擊圖片不同區域響應不同的事件