Skip to main content

polyhorn_ios_sys/uikit/
image.rs

1use objc::runtime::*;
2use objc::*;
3
4use crate::coregraphics::CGSize;
5use crate::foundation::{NSData, NSString};
6use crate::Raw;
7
8/// An object that manes image data in your app.
9pub struct UIImage {
10    object: *mut Object,
11}
12
13unsafe impl Send for UIImage {}
14unsafe impl Sync for UIImage {}
15
16impl UIImage {
17    /// Creates an image object from the specified named asset.
18    pub fn with_name(name: &str) -> Option<UIImage> {
19        unsafe {
20            let name = NSString::from(name);
21            let object: *mut Object = msg_send![class!(UIImage), imageNamed: name.as_raw()];
22
23            if object.is_null() {
24                None
25            } else {
26                Some(UIImage {
27                    object: objc_retain(object),
28                })
29            }
30        }
31    }
32
33    /// Creates and returns an image object that uses the specified image data.
34    pub fn with_data(bytes: &[u8]) -> Option<UIImage> {
35        unsafe {
36            let data = NSData::from(bytes);
37            let object: *mut Object = msg_send![class!(UIImage), imageWithData: data.as_raw()];
38
39            if object.is_null() {
40                None
41            } else {
42                Some(UIImage {
43                    object: objc_retain(object),
44                })
45            }
46        }
47    }
48
49    /// Returns a copy of this image with template rendering mode.
50    pub fn templated(&self) -> UIImage {
51        unsafe {
52            let object: *mut Object = msg_send![self.object, imageWithRenderingMode: 2 as usize];
53
54            UIImage {
55                object: objc_retain(object),
56            }
57        }
58    }
59
60    /// The logical dimensions, in points, for the image.
61    pub fn size(&self) -> CGSize {
62        unsafe { msg_send![self.object, size] }
63    }
64}
65
66impl Raw for UIImage {
67    unsafe fn from_raw(object: *mut Object) -> Self {
68        UIImage { object }
69    }
70
71    unsafe fn as_raw(&self) -> *mut Object {
72        self.object
73    }
74}
75
76impl Clone for UIImage {
77    fn clone(&self) -> Self {
78        unsafe { Self::from_raw_retain(self.as_raw()) }
79    }
80}
81
82impl Drop for UIImage {
83    fn drop(&mut self) {
84        unsafe { objc_release(self.object) }
85    }
86}