I'm looking for a way to make a red box Entity with custom white dotted outlined borders.
I'm really new to RealityKit, is that something I should be able to achieve programmatically?
What I have so far:
class Box: Entity, HasModel, HasAnchoring {
convenience init(color: UIColor, position: SIMD3<Float>) {
self.init()
model = ModelComponent(
mesh: .generateBox(size: 0.1)
materials: [
SimpleMaterial(color: color, isMetallic: false)
]
)
position = position
}
}
That story is about UV-mapping of a model made in 3D authoring tool, or, if you want to do it programmatically, it's about Metal (vertices, edges, faces and uv-vertices). At the moment in RealityKit 2.0 there is no tools to uvmap a border of a model.
You can read about MTLTexture here.
I have a map layer that has a remote GeoJSON source. I'm adding it to my Mabpox map using the MGLShapeCollectionFeature and then use the MGLCircleStyleLayer and a MGLSymbolStyleLayer to display the data along with some text.
It works as expected and the points are displayed on the map:
Data
{
"features": [
{
"geometry": {
"coordinates": [
-120.644,
35.238
],
"type": "Point"
},
"properties": {
"altim": 1019.0,
"cover": "CLR",
"data": "METAR",
"dewp": 12.2,
"fltcat": "VFR",
"id": "KSBP",
"obsTime": "2020-05-03T18:56:00Z",
"prior": "5",
"rawOb": "KSBP 031856Z 31018KT 10SM CLR 22/12 A3009 RMK AO2 SLP187 T02170122",
"site": "San Luis Obispo/Ches",
"slp": 1018.7,
"temp": 21.7,
"visib": 10.00,
"wdir": 310,
"wspd": 18
},
"type": "Feature"
}
],
"type": "FeatureCollection"
}
Result
Now the question is if it's possible to display the data as a rounded rectangle instead of just a circle. Something like this:
This can be done by using not a single position, but a polygon built from a position array in shape of a rounded rectangle. This rectangle can be filled with a pattern the text you would like to show.
Load fill pattern:
// Set the UIImage to be used for the fill pattern.
let fillPatternImage = UIImage(named: "stripe-pattern")!
// Add the fill pattern image to used by the style layer.
style.setImage(fillPatternImage, forName: "stripe-pattern")
With layer from a vector source (Positions Polygon array defining the rounded rectangle)
// Create a style layer using the vector source.
let layer = MGLFillStyleLayer(identifier: "drone-restrictions-style", source: source)
Add the filling pattern and set the opacity of the pattern:
layer.fillPattern = NSExpression(forConstantValue: "stripe-pattern")
layer.fillOpacity = NSExpression(forConstantValue: 0.5)
Use a separate layer to draw the text over the rounded rectangle.
Please also refer to this Mapbox example
In ARKit 2.0, I am trying to use PBR base material. Using 3D model in .obj file format.
Problem: I am not able see the dark product. I am not sure, if it's related to set proper lighting in SceneKit. Please help me how to set PBR base lighting in ARKit/SceneKit.
Try below code:
//Set lighting
let light = SCNLight()
light.type = .ambient
node.light = light
// if light estimation is enabled, update the intensity
// of the model's lights and the environment map
if let lightEstimate = self.session.currentFrame?.lightEstimate {
self.enableEnvironmentMapWithIntensity(lightEstimate.ambientIntensity / 1000.0)
} else {
self.enableEnvironmentMapWithIntensity(6)
}
// Call environment Map
func enableEnvironmentMapWithIntensity(_ intensity: CGFloat) {
if sceneView.scene.lightingEnvironment.contents == nil {
if let environmentMap = UIImage(named: "Models.scnassets/sharedImages/environment_blur.exr") {
sceneView.scene.lightingEnvironment.contents = environmentMap
}
}
sceneView.scene.lightingEnvironment.intensity = intensity
}
Required Result : http://prntscr.com/luwlax
For reference, attaching PBR Materials:
Diffuse : https://prnt.sc/luwc40
Roughness : https://prnt.sc/luwcl7
Normal : https://prnt.sc/luwcuw
Metalness : https://prnt.sc/luwdaz
If you have a separated geometry (a screen separately from frame), it's easy to assign texture onto these parts.
If you have a combined geometry (all parts as one piece) the only way to texture such a model is to assign pre-made UV-mapped texture.
hello I have problem loading some image using the following code:
xtension UIImageView {
func downloadImage(from urlRequest: String) {
let urlRequest = URLRequest(url: (URL(string: urlRequest.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!)!))
urlRequest.adding
let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
print(urlRequest)
if error != nil {
print(error!)
return
}
let httpResponse = response as! HTTPURLResponse
let statusCode = httpResponse.statusCode
if (statusCode == 200) {
DispatchQueue.main.async {
self.image = UIImage(data: data!)!
}
}
}
task.resume()
}
}
from what i saw it appears my URL string is being changed from:
https://upload.wikimedia.org/wikipedia/commons/5/5f/Panthera_pardus_%28Leopard_%28Kongo%29%29.jpg
(which is a valid url)
into:
https://upload.wikimedia.org/wikipedia/commons/5/5f/Panthera_pardus_%2528Leopard_%2528Kongo%2529%2529.jpg
perhaps there is something wrong with my parsing from json?
json parse code:
private func readJson() {
do {
self.animals = [Animal]()
if let file = Bundle.main.url(forResource: "animals", withExtension: "json") {
let data = try Data(contentsOf: file)
let json = try JSONSerialization.jsonObject(with: data, options: [])
if let object = json as? [String: Any] {
//parse title:
if (object["title"] as? String) != nil {
}
var isAnimal: Bool
//parse the paragrapphs which is an array
if let paragraphs = object["paragraphs"] as? [[String: AnyObject]] {
for paragraph in paragraphs {
isAnimal = true
let caption = paragraph["caption"]
let text = paragraph["text"]
if let images = paragraph["images"] as? [[String:AnyObject]] {
if images.count == 0 {
isAnimal = false
}
var imageObjects = [[String:String]]()
for image in images {
let imageName = image["name"] as? String
let imageUrl = image["url"] as? String
let imageExplanation = image["explanation"] as? String
var imgDict = [String: String]()
imgDict["name"] = imageName
imgDict["url"] = imageUrl
imgDict["explanation"] = imageExplanation
imageObjects.append(imgDict)
}
if isAnimal == true {
let animal = Animal()
animal.caption = caption as! String?
animal.text = text as! String?
animal.images = imageObjects
self.animals?.append(animal)
}
}
}
}
// json is a dictionary
// print(object)
} else if let object = json as? [Any] {
// json is an array
print(object)
} else {
print("JSON is invalid")
}
} else {
print("no file")
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
} catch {
print(error.localizedDescription)
}
}
and the json file:
{
"title": "Wildlife of South Africa",
"paragraphs": [
{
"caption": "Introduction",
"text": "South Africa has a large variety of wildlife, including snakes, birds, plains animals, and predators. The country has 299 species of mammals and 858 species of birds.",
"images": []
},
{
"caption": "Cape Buffalo",
"text": "The Cape Buffalo, also known as the African cook, is a powerful animal that has few natural enemies. Their power and size means that they are very much able to defend themselves. They have been known to kill lions, hyena, humans, and other wild predators. Because of this they have taken their place in the African big five, elephants, lions, Cape buffalo, rhinoceroses, and leopards. (The big five are known to be some of the most dangerous and aggressive animals in Africa.) Another African name for the Cape buffalo is black death, because of their colour and their aggressive behaviour.",
"images": [
{
"name": "Cape buffalo",
"url": "https://upload.wikimedia.org/wikipedia/commons/c/cb/African_Buffalo.JPG",
"explanation": "The African buffalo or Cape buffalo (Syncerus caffer) is a large African bovine. It is not closely related to the slightly larger wild water buffalo of Asia and its ancestry remains unclear. Syncerus caffer caffer, the Cape buffalo, is the typical subspecies, and the largest one, found in South and East Africa. S. c. nanus (African forest buffalo) is the smallest subspecies, common in forest areas of Central and West Africa, while S. c. brachyceros is in West Africa and S. c. aequinoctialis is in the savannas of Central Africa. The adult buffalo's horns are its characteristic feature; they have fused bases, forming a continuous bone shield across the top of the head referred to as a \"boss\". They are widely regarded as very dangerous animals, as they gore and kill over 200 people every year."
}
]
},
{
"caption": "Gemsbok",
"text": "The African oryx gazelle also known as gemsbuck or gemsbok are African plains animals that travel in groups of 10-45. The gemsbuck's groups are set up with a dominant male and in most cases a few dominant females. Male's horns are straight and pointed at the tip. Because of this they have been known to impale attacking lions. Female horns can be the same but sometimes they are curved backward. There are two different varieties of gemsbok, the southern and the northern. The southern variety have longer horns and the northern have black fringed ears. The northern gemsbok are rarely seen in South Africa.",
"images": [
{
"name": "Gemsbok",
"url": "https://upload.wikimedia.org/wikipedia/commons/c/cd/Oryx_gazella_PICT1415.JPG",
"explanation": "Gemsbok are light brownish-grey to tan in colour, with lighter patches toward the bottom rear of the rump. Their tails are long and black in colour. A blackish stripe extends from the chin down the lower edge of the neck, through the juncture of the shoulder and leg along the lower flank of each side to the blackish section of the rear leg. They have muscular necks and shoulders, and their legs have white 'socks' with a black patch on the front of both the front legs, and both genders have long, straight horns. Comparably, the East African oryx lacks a dark patch at the base of the tail, has less black on the legs (none on the hindlegs), and less black on the lower flanks. One very rare condition is the \"Golden Oryx\", in which the Gemsboks black markings are muted and now appear golden. Gemsbok are the largest species in the Oryx genus. They stand about 1.2 m (3.9 ft) at the shoulder. The body length can vary from 190 to 240 cm (75 to 94 in) and the tail measures 45 to 90 cm (18 to 35 in). Male gemsbok can weigh between 180 and 240 kg (400 and 530 lb), while females weigh 100–210 kg (220–460 lb)."
}
]
},
{
"caption": "Kudu",
"text": "The kudu are split into two different groups, greater kudu and lesser kudu. The greater kudu are regularly found in South Africa. Like the gemsbok, kudu are African antelope. They are fast and stealthy. They are a brown-grey colour with white stripes that go down the centre of their body. For those two facts their African name is grey ghost. The males have tall spiraling horns, females regularly have no horns. Kudu are peaceful and are normally not dangerous.",
"images": [
{
"name": "Greater kudu",
"url": "https://upload.wikimedia.org/wikipedia/commons/c/c8/KuduKrüger.jpg",
"explanation": "Greater kudus have a narrow body with long legs, and their coats can range from brown/bluish grey to reddish brown. They possess between 4 and 12 vertical white stripes along their torso. The head tends to be darker in colour than the rest of the body, and exhibits a small white chevron which runs between the eyes."
},
{
"name": "Lesser kudu",
"url": "https://upload.wikimedia.org/wikipedia/commons/5/5e/Lesser_Kudu.jpg",
"explanation": "The lesser kudu (Tragelaphus imberbis) is a forest antelope found in East Africa. It is placed in the genus Tragelaphus and family Bovidae. It was first described by the English zoologist Edward Blyth in 1869. The head-and-body length is typically 110–140 cm (43–55 in). Males reach about 95–105 cm (37–41 in) at the shoulder, while females reach 90–100 cm (35–39 in). Males typically weigh 92–108 kg (203–238 lb) and females 56–70 kg (123–154 lb). The females and juveniles have a reddish-brown coat, while the males become yellowish grey or darker after the age of two years. Horns are present only on males. The spiral horns are 50–70 cm (20–28 in) long, and have two to two-and-a-half twists."
}
]
},
{
"caption": "Leopards",
"text": "Leopards are the most reclusive of the big cats. They are opportunistic hunters and will prey upon smaller mammals and rodents when other food sources are unavailable. The diet of leopards consists primarily of ungulates such as Thomson's gazelles. Leopards have relatively small physical builds in comparison to lions and therefore choose to hunt nocturnally to prevent the possibility of confrontation. In order to protect themselves and preserve their kills, leopards have developed exceptional climbing skills, allowing them to scale.",
"images": [
{
"name": "African leopard",
"url": "https://upload.wikimedia.org/wikipedia/commons/c/c5/Leopard_africa.jpg",
"explanation": "The leopard (Panthera pardus) /ˈlɛpərd/ is one of the five \"big cats\" in the genus Panthera. It is a member of the family Felidae with a wide range in sub-Saharan Africa and parts of Asia. Fossil records found in Italy suggest that in the Pleistocene it ranged as far west as Europe and as far east as Japan. Compared to other members of Felidae, the leopard has relatively short legs and a long body with a large skull. It is similar in appearance to the jaguar, but has a smaller, lighter physique. Its fur is marked with rosettes similar to those of the jaguar, but the leopard's rosettes are smaller and more densely packed, and do not usually have central spots as the jaguar's do. Both leopards and jaguars that are melanistic are known as black panthers."
},
{
"name": "Leopard skin",
"url": "https://upload.wikimedia.org/wikipedia/commons/5/5f/Panthera_pardus_%28Leopard_%28Kongo%29%29.jpg",
"explanation": "Dark-coloured leopard skin"
}
]
},
{
"caption": "Snakes",
"text": "Lots of frickin' dangerous snakes out there - you have been warned, dudettes!",
"images": [
{
"name": "Eastern green mamba",
"url": "https://upload.wikimedia.org/wikipedia/commons/9/9e/Mamba_Dendroaspis_angusticeps.jpg",
"explanation": "The eastern green mamba (Dendroaspis angusticeps), also known as the common mamba, East African green mamba, green mamba, or white-mouthed mamba, is a large, tree-dwelling, highly venomous snake species of the mamba genus Dendroaspis. This species of mamba was first described by a Scottish surgeon and zoologist in 1849. This snake mostly inhabits the coastal regions of southern East Africa. Adult females average approximately 2.0 metres (6.6 ft) in length, and males are slightly smaller. Eastern green mambas prey on birds, eggs, bats, and rodents such as mice, rats, and gerbils. They are shy and elusive snakes which are rarely seen, making them somewhat unusual among mambas, and elapids in general. This elusiveness is usually attributed to the species' green colouration which blends with its environment, and its arboreal lifestyle. However, eastern green mambas have also been observed to use \"sit-and-wait\" or ambush predation like many vipers, unlike the active foraging style typical of other elapids, which may be a factor in the rarity of sightings."
},
{
"name": "Black mamba",
"url": "https://upload.wikimedia.org/wikipedia/commons/7/76/Dendroaspis_polylepis_%2814%29.jpg",
"explanation": "The black mamba (Dendroaspis polylepis) is a venomous snake endemic to parts of sub-Saharan Africa. Specimens vary in color from grey to dark brown, but not black. Juvenile black mambas tend to be lighter in color than adults and darken with age. It is the longest species of venomous snake indigenous to the African continent; mature specimens generally exceed 2 meters (6.6 ft) and commonly attain 3 meters (9.8 ft). Specimens of 4.3 to 4.5 meters (14.1 to 14.8 ft) have been reported."
},
{
"name": "Cape cobra",
"url": "https://upload.wikimedia.org/wikipedia/commons/3/3c/Naja_nivea.jpg",
"explanation": "The Cape cobra (Naja nivea), also called the yellow cobra is a moderate-sized, highly venomous species of cobra inhabiting a wide variety of biomes across southern Africa including arid savanna, fynbos, bushveld, desert and semi-desert regions. The species is diurnal and is a feeding generalist, preying on a number of different species and carrion. Predators of this species include birds of prey, honey badgers and various species of mongoose. The Cape cobra is also known as the \"geelslang\" (yellow snake) and \"bruinkapel\" (brown cobra) in South Africa. Afrikaans speaking South Africans also refer to the Cape cobra as \"koperkapel\" (\"copper cobra\"), mainly because of a rich yellow colour variation. This species has no known subspecies."
}
]
}
]
}
edit:
code for image to download:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if !(self.animals?[indexPath.item].hasMultipleImages())! {
let cell = tableView.dequeueReusableCell(withIdentifier: "animalCell", for: indexPath) as! AnimalCell
cell.name.text = self.animals?[indexPath.item].caption
cell.info.text = self.animals?[indexPath.item].text
cell.imgView.downloadImage(from: (self.animals?[indexPath.item].images?[0]["url"])!)
cell.imgView.accessibilityIdentifier = self.animals?[indexPath.item].images?[0]["name"]
cell.imgView?.isUserInteractionEnabled = true
cell.imgView?.tag = indexPath.row
let tapped:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.TappedOnImage(sender:)))
tapped.numberOfTapsRequired = 1
cell.imgView?.addGestureRecognizer(tapped)
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "animalCellTwo", for: indexPath) as! AnimaCellTwo
cell.name.text = self.animals?[indexPath.item].caption
cell.info.text = self.animals?[indexPath.item].text
cell.imgViewLeft.downloadImage(from: (self.animals?[indexPath.item].images?[0]["url"])!)
cell.imgViewLeft.accessibilityIdentifier = self.animals?[indexPath.item].images?[0]["name"]
cell.imgViewLeft?.isUserInteractionEnabled = true
cell.imgViewLeft?.tag = indexPath.row
cell.imgViewRight.downloadImage(from: (self.animals?[indexPath.item].images?[1]["url"])!)
cell.imgViewRight.accessibilityIdentifier = self.animals?[indexPath.item].images?[1]["name"]
cell.imgViewRight?.isUserInteractionEnabled = true
cell.imgViewRight?.tag = indexPath.row
let tapped:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.TappedOnImage(sender:)))
tapped.numberOfTapsRequired = 1
cell.imgViewLeft?.addGestureRecognizer(tapped)
cell.imgViewRight?.addGestureRecognizer(tapped)
return cell
}
}
basically I have a uitableview with 2 different prototype tableviewcells:
one cell has one image + 2 labes , and the other has 2 images + 2 labels
I am trying to load them to the table I also need to implement caching for images to prevent downloading them everytime upon scrolling, I hope anyone could help I am trying to solve this for 2 days now... :|
Try to encode your image string
let encodedHost = imageUrl.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
OR
Replace character
imageUrl = imageUrl.replacingOccurrences(of: "%25", with: "", options: .literal, range: nil)
I'm looking to achieve an effect similar to that in this example.
However, the above example uses a gradient that is relative to the visible plot. So the 0 stop color is used at the peak of the visible plot (whatever the actual value of the peak), and the 1 stop color is used at the base.
Say I have data that can range from 0 to 100 (e.g. a percentage). I want to be able to specify that "dark" is always used for a value of 100, while "light" is always used for a value of 0.
So, if my visible data only ranges from 0 to 20, then this is all filled with a light-ish gradient colour (at the lower end of the gradient spectrum)... I don't want it to be filled from light to fully dark.
Any way to achieve this?
To achieve such gradient, you need to do a few things.
Gradient units should be switched to userSpaceOnUse.
x1, y1, x2, y2 should point to the points where the plot area starts and ends.
You do not know what would be the plot area, so you have to set the gradient on load event.
function() {
this.series[0].update({
fillColor: {
linearGradient: [0, 0, 0, this.plotHeight]
}
});
}
example: http://jsfiddle.net/qhuee8uf/1/
Now, the gradient has fixed x/y attributes, what means that the gradient will not be responsive. To have a gradient which will work with a resizing chart, you should recalculate gradient on redraw event.
Also, I have found that updating gradient in the series does not update the gradient but creates a new one - which might be not be the best behaviour to have.
Instead, you can modify the gradient attributes directly
function adjustGradient() {
document.getElementsByTagName('linearGradient')[0].setAttributeNS(null, 'y2', this.plotHeight);
}
chart: {
events: {
load: adjustGradient,
redraw: adjustGradient
}
},
example: http://jsfiddle.net/qhuee8uf/