i have control gradiant background. on mousedown
or mouseup
event want capture color pixel immeidately under mouse pointer. how that?
i created behavior can attached image object grab color, 100% wpf. here behavior; tweaked work "visual", not image.
[note: hardcoded 96dpi creation of rendertargetbitmap... milage may vary]
using system.componentmodel; using system.windows; using system.windows.controls; using system.windows.input; using system.windows.interactivity; using system.windows.media; using system.windows.media.imaging; namespace company.solution.project.utilities.behaviors { [description("used sample color under mouse image when mouse pressed. ")] public class imagebehaviormousedownpointsampletocolor : behavior<image> { public static readonly dependencyproperty selectedcolorproperty = dependencyproperty.register("selectedcolor", typeof(color), typeof(imagebehaviormousedownpointsampletocolor), new uipropertymetadata(colors.white)); public color selectedcolor { { return (color)getvalue(selectedcolorproperty); } set { setvalue(selectedcolorproperty, value); } } protected override void onattached() { base.onattached(); associatedobject.mousemove += associatedobject_mousemove; associatedobject.mousedown += associatedobject_mousedown; } protected override void ondetaching() { base.ondetaching(); associatedobject.mousemove -= associatedobject_mousemove; associatedobject.mousedown -= associatedobject_mousedown; } private void associatedobject_mousedown(object sender, mousebuttoneventargs e) { samplepixelforcolor(); } private void associatedobject_mousemove(object sender, mouseeventargs e) { if (e.leftbutton == mousebuttonstate.pressed) { samplepixelforcolor(); } } private void samplepixelforcolor() { // retrieve coordinate of mouse position in relation supplied image. point point = mouse.getposition(associatedobject); // use rendertargetbitmap visual, in case image has been transformed. var rendertargetbitmap = new rendertargetbitmap((int)associatedobject.actualwidth, (int)associatedobject.actualheight, 96, 96, pixelformats.default); rendertargetbitmap.render(associatedobject); // make sure point within dimensions of image. if ((point.x <= rendertargetbitmap.pixelwidth) && (point.y <= rendertargetbitmap.pixelheight)) { // create cropped image @ supplied point coordinates. var croppedbitmap = new croppedbitmap(rendertargetbitmap, new int32rect((int)point.x, (int)point.y, 1, 1)); // copy sampled pixel byte array. var pixels = new byte[4]; croppedbitmap.copypixels(pixels, 4, 0); // assign sampled color solidcolorbrush , return conversion. selectedcolor = color.fromargb(255, pixels[2], pixels[1], pixels[0]); } } } }
Comments
Post a Comment