9
$\begingroup$

I want to make an interface where a user can fill in a square grid by clicking. Some processing will then be done with these pixels to produce a new picture. How can I make this clickable interface? I thought about linking each little square to a set of mouse positions, but this seems unnecessarily complicated.

Grid

$\endgroup$

3 Answers 3

15
$\begingroup$

just select n for a nxn grid

n = 5;
Grid[Partition[
Table[DynamicModule[{col = White}, 
EventHandler[
 Dynamic[Graphics[{EdgeForm[Thick], col, Rectangle[]}, 
   ImageSize -> 
    Tiny]], {"MouseClicked" :> (col = 
     col /. {Black -> White, White -> Black})}]], {n^2}], n]]

here is the result

enter image description here

$\endgroup$
2
  • $\begingroup$ Is there a way to get the information out of the picture e.g. {{0,0,0},{1,1,1},{0,1,0}} for a 3x3 grid? $\endgroup$
    – gilianzz
    Commented Nov 3, 2018 at 18:55
  • $\begingroup$ @gilianzz I found a way to do this and posted an answer $\endgroup$
    – ZaMoC
    Commented Nov 3, 2018 at 23:27
5
$\begingroup$
n = 10;
m = ConstantArray[0, {n, n}];
Row[{Dynamic[EventHandler[ArrayPlot[m, Mesh -> All, ImageSize -> 300], 
  {"MouseClicked" :> With[{p = Reverse[{1, n} + {1, -1} Floor@MousePosition["Graphics"]]},
   m[[## & @@ p]] = m[[## & @@ p]] /. {0 -> 1, 1 -> 0}]}]], 
 Dynamic[Style[MatrixForm[m], 24]]}, Spacer[20]]

enter image description here

$\endgroup$
2
  • 1
    $\begingroup$ I think you should use Mesh -> True in ArrayPlot $\endgroup$
    – ZaMoC
    Commented Nov 4, 2018 at 1:33
  • $\begingroup$ good idea, thanks @J42161217. $\endgroup$
    – kglr
    Commented Nov 4, 2018 at 3:49
1
$\begingroup$

I think I found a "way to get the information out of the picture"

First Run the code in the first answer

Let's say you get

Out[15]=....(Grid)...   

then you manipulate the grid and when you are done you must "run" (shift+enter) the final grid.

so, you'll get a new output like

 Out[17]=....(Grid)...    

we are interested in the number "17" of the final output.
you take this number and place it in the begining of the function below

out = %17;
Map[ToExpression[(Characters @@ StringCases[ToString@InputForm[
      #], "vel[" ~~ __ ~~ "]}, E"])[[5]]] &, 
First[out], {2}] /. {0 -> 1, 1 -> 0}   

this will give you the result you asked in the comment of the first answer

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.