Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add ClippingRect #1450

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 38 additions & 12 deletions src/sdl2/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,16 @@ impl RenderTarget for Window {
type Context = WindowContext;
}

#[derive(Clone, Copy, Debug)]
pub enum ClippingRect {
/// a non-zero area clipping rect
Some(Rect),
/// a clipping rect with zero area
Zero,
/// the absence of a clipping rect
None,
}

/// Methods for the `WindowCanvas`.
impl Canvas<Window> {
/// Gets a reference to the associated window of the Canvas
Expand Down Expand Up @@ -1099,31 +1109,47 @@ impl<T: RenderTarget> Canvas<T> {
}

/// Sets the clip rectangle for rendering on the specified target.
///
/// If the rectangle is `None`, clipping will be disabled.
#[doc(alias = "SDL_RenderSetClipRect")]
pub fn set_clip_rect<R: Into<Option<Rect>>>(&mut self, rect: R) {
let rect = rect.into();
// as_ref is important because we need rect to live until the end of the FFI call, but map_or consumes an Option<T>
let ptr = rect.as_ref().map_or(ptr::null(), |rect| rect.raw());
let ret = unsafe { sys::SDL_RenderSetClipRect(self.context.raw, ptr) };
pub fn set_clip_rect(&mut self, arg: ClippingRect) {
let ret = match arg {
ClippingRect::Some(r) => {
unsafe { sys::SDL_RenderSetClipRect(self.context.raw, r.raw()) }
}
ClippingRect::Zero => {
let r = sys::SDL_Rect {
x: 0,
y: 0,
w: 0,
h: 0,
};
let r: *const sys::SDL_Rect = &r;
unsafe { sys::SDL_RenderSetClipRect(self.context.raw, r) }
}
ClippingRect::None => {
unsafe { sys::SDL_RenderSetClipRect(self.context.raw, ptr::null()) }
}
};
if ret != 0 {
panic!("Could not set clip rect: {}", get_error())
}
}

/// Gets the clip rectangle for the current target.
///
/// Returns `None` if clipping is disabled.
#[doc(alias = "SDL_RenderGetClipRect")]
pub fn clip_rect(&self) -> Option<Rect> {
pub fn clip_rect(&self) -> ClippingRect {
let clip_enabled = unsafe { sys::SDL_RenderIsClipEnabled(self.context.raw) };

if let sys::SDL_bool::SDL_FALSE = clip_enabled {
return ClippingRect::None;
}

let mut raw = mem::MaybeUninit::uninit();
unsafe { sys::SDL_RenderGetClipRect(self.context.raw, raw.as_mut_ptr()) };
let raw = unsafe { raw.assume_init() };
if raw.w == 0 || raw.h == 0 {
None
ClippingRect::Zero
} else {
Some(Rect::from_ll(raw))
ClippingRect::Some(Rect::from_ll(raw))
}
}

Expand Down