How can I constrain locators to a limited (but not regular) set of positions?

泄露秘密 提交于 2019-12-05 09:58:22

This appears to work.

myTicks = {-.9, 0, .1, .2, .45, .79, 1};

DynamicModule[{p = {.25, 0}, p2 = {.75, 0}},
 LocatorPane[Dynamic[{p, p2}], 
  Graphics[{}, Axes -> {True, False}, 
   PlotLabel -> 
    Row[{"locators at: ", 
      Dynamic[p[[1]] = Nearest[myTicks, p[[1]]][[1]]], " and ", 
      Dynamic[p2[[1]] = Nearest[myTicks, p2[[1]]][[1]]]}], 
   Ticks -> {myTicks, Automatic}], {{{-.9, 0}, {1, 0}}}, ContinuousAction -> False]
]

Let's try this:

pts = {{0, 0}, {10, 0}};
myTics = Table[{x, 0}, {x, 0, 10, 5}];
LocatorPane[Dynamic[pts],
 ListPlot[myTics, PlotRange -> {{-1, 11}, {-1, 1}}, 
  PlotStyle -> Directive[PointSize[.07], Red],
  Epilog -> {PointSize[.05], Blue, h = Point[Dynamic[{Nearest[myTics, pts[[1]]]}]], 
             PointSize[.03], Yellow, j = Point[Dynamic[{Nearest[myTics, pts[[2]]]}]], 
             Black, 
              Text[{"locators at: ", Dynamic[h[[1, 1]]], " and ",Dynamic[j[[1, 1]]]}, 
                    {5, .5}]}],
 Appearance -> None]

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!