简体   繁体   中英

How to draw a rectangle in xamarin.mac

I'm trying to draw a rectangle in the xamarin.mac framework. It seems like this can be accomplished with the CoreGrpahics namespace but I'm not sure how it hooks up with xamarin. For example

        NSColor.Black.Set();
        NSBezierPath.StrokeLine(new CGPoint(-10.0f, 0.0f), new CGPoint(10.0f, 0.0f));

Does not make anything appear on the screen, when i believe it should make a single line appear. This seems trivial in the other Xamarin. frameworks as there are built in functions available, but the xamarin.mac documentation is very sparse.

Welcome! Glad to see more Xamarin.Mac users.

@SushiHangover hinted at it but you need to be in a valid draw context. Pardon if I'm over-explaining, but custom drawing like you're discussing is often done in a NSView, typically by overriding a view's DrawRect(CGRect dirtyRect) method. That method is inherently called by AppKit within the proper graphics context. So your code would work fine if called within that method of a view. Keep in mind that those drawing methods are called very often and must be efficient.

If you were to use a CGPath instead of a NSBezierPath, you need to add that path to the context by calling NSGraphicsContext.CurrentContext.CGContext.addPath(path) .

I've made a little Xamarin workbook titled "MacOS Custom Drawing" for ya here that shows both ways: https://github.com/NickSpag/Workbooks . I'd also recommend Workbooks for drawing practice and testing, as they make it very easy to continually and quickly reload your code.

this code from the Xamarin docs draws a triangle, but should give you the basic idea. The CoreGraphics API should be the same for iOS and Mac, so an example for one should easily translate to the other

//get graphics context
using (CGContext g = UIGraphics.GetCurrentContext ()) {

    //set up drawing attributes
    g.SetLineWidth (10);
    UIColor.Blue.SetFill ();
    UIColor.Red.SetStroke ();

    //create geometry
    var path = new CGPath ();

    path.AddLines (new CGPoint[]{
    new CGPoint (100, 200),
    new CGPoint (160, 100), 
    new CGPoint (220, 200)});

    path.CloseSubpath ();

    //add geometry to graphics context and draw it
    g.AddPath (path);       
    g.DrawPath (CGPathDrawingMode.FillStroke);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM