5
$\begingroup$

I would like to "write" on to a matrix using the mouse. That is, I would like to use the integer value of Locator coordinates (p) to index a matrix. Then, if the mouse button is down, write a 1 in that location. That approach doesn't seem to work since, when attempting to do something like M[[Sequence @@ Round [p]]], the coordinate p is actually a dynamic quantity, which can't be converted to two integer indices by Sequence @@ Round.

Is there any way to do this? or, Is there an equivalent workaround that gets the same result. The simplest example would be using the mouse to input a freehand black and white drawing as pixels on a matrix, which could later be subject to image processing algorithms.

$\endgroup$
2

1 Answer 1

5
$\begingroup$
Manipulate[x = ConstantArray[0, 9 {1, 1}];
 Row[{EventHandler[Dynamic[tds = Reverse[Transpose[x]];
     MatrixPlot[tds, PlotRangePadding -> 0, Mesh -> All, 
      ImageSize -> {300, 300}, 
      ColorRules -> {1 -> Black, 
        0 -> None}]], {"MouseClicked" :> (pos = 
        Ceiling[MousePosition["Graphics"]];
       x = ReplacePart[x, pos -> 1 - x[[Sequence @@ pos]]];)}], 
   Dynamic@Magnify[MatrixForm[tds], 2]}], {pos, 
  ControlType -> None}, {x, ControlType -> None}, {tds, 
  ControlType -> None}, AppearanceElements -> None, FrameMargins -> 0]

enter image description here

$\endgroup$
3
  • $\begingroup$ Nice! A click and drag to fill would be a nice addition :) $\endgroup$
    – rm -rf
    Apr 3, 2013 at 1:59
  • $\begingroup$ @rm-rf thanks ;) $\endgroup$ Apr 3, 2013 at 3:25
  • $\begingroup$ And now you're most of the way to a game of minesweeper! $\endgroup$
    – bill s
    Apr 3, 2013 at 7:01

Your Answer

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

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