SwiftUI - Random word animation with letters scrolling
I would like to implement a random word generator, shaped similar as to a Cryptex. I would like to have the single letters that rotate in a "wheel picker style" (as if the system was going through all the letters of the alphabet to pick the right ones) and that one at a time they'd stop to reveal the word.
I have implemented a string that gets randomized, with the single letters that all have individual 3d rotation animation. However, I have no idea on how to go from here to the result I'd like to have. In the code listed here below there's also a function that I created to generate the delay, so each letter could animate a bit longer. I tried adding this func to the duration value of the Animation, but with that the animation stops working. I left the func anyway, in case it might be useful.
import SwiftUI
import Foundation
struct ContentView: View {
@State private var degrees = 0.0
var words = ["One", "Two", "Three", "Four", "Five", "Six", "Seven"]
@State var text = "???"
var body: some View {
VStack {
HStack(spacing: 0) {
ForEach(Array(text), id: \.self) { letters in
Text(String(letters))
.fontWeight(.semibold)
.foregroundColor(.green)
.font(.system(size: 30))
.rotation3DEffect(.degrees(degrees), axis: (x: 1, y: 0, z: 0))
.animation(Animation.linear(duration: 3).speed(10), value: degrees)
}
}
Button {
withAnimation {
self.degrees += 720
let randomIndex = Int.random(in: 0...(words.count-1))
text = words[randomIndex]
}
} label: {
Text("Get a random word!")
.foregroundColor(.black)
}
.padding(.top, 40)
}
}
func generateDelay(letter: String.Element) -> Double {
let delayFromIndex : Double = Double(Array(text).firstIndex(where: { $0 == letter }) ?? 0)
let delay : Double = 3 + delayFromIndex
return delay
}
}
extension ForEach where Data.Element: Hashable, ID == Data.Element, Content: View {
init(values: Data, content: @escaping (Data.Element) -> Content) {
self.init(values, id: \.self, content: content)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
do you know?
how many words do you know
See also questions close to this topic
- Broken project in XCODE objective c
-
Lokalise: How to change default NSStringFormatValueTypeKey
The default
NSStringFormatValueTypeKey
property in Lokalise always returns the stringli
. In my code, the stringd
.When exporting the modified stringsdict file from Lokalise to Github, the
NSStringFormatValueTypeKey
is alwaysli
. Currently, there is no way to change this hardcoded value in the Lokalise platform. What is a trick to change the value besides manually changing them in the stringsdict file in Xcode? I want to change the value tod
Export from Lokalise:
<key>plural.day</key> <dict> <key>NSStringLocalizedFormatKey</key> <string>%#@day@</string> <key>day</key> <dict> <key>NSStringFormatSpecTypeKey</key> <string>NSStringPluralRuleType</string> <key>NSStringFormatValueTypeKey</key> <string>li</string> <key>one</key> <string></string> <key>other</key> <string></string> </dict> </dict>
Desired outcome:
<key>plural.day</key> <dict> <key>NSStringLocalizedFormatKey</key> <string>%#@day@</string> <key>day</key> <dict> <key>NSStringFormatValueTypeKey</key> <string>d</string> <key>NSStringFormatSpecTypeKey</key> <string>NSStringPluralRuleType</string> <key>one</key> <string>%d day ago</string> <key>other</key> <string>%d days ago</string> </dict> </dict>
-
Xcode clean build folder command not working
Not sure what happened but suddenly, my xcode clean build folder option under Product -> Clean Build Folder no longer works. Instead it gives me an error:
Could not delete
/Users/...build
because it was not created by the build system.Is there a way I can reset the xcode settings? Or does someone have any idea how to fix this?
-
Rotate and translate image from center to all directions one by one in ios swift
I am trying to make a demo of animation for learning but i am having issue regarding coordinate system of apple and how does it work when trying for animations. The issue is i have 6 static images stacked upon each other as pile of playing cards and have 6 empty views in all directions which is of same height and width as the pile cards height width. Now how do i rotate and translate card 6 to bottomleft then card 5 to topleft then card 4 to top center card3 to topright then card 2 to bottom right and card1 to bottom center i.e more like a playing card distribution animation
-
Javascript request animation frame irregular translation
SO community! I'm trying to make an object move at the same phase as scroll using CSS transform. The problem is that I see the animation is not smooth. Instead, is like the box is flickering and 'jumping' all the time, and I can't figure out the cause.
How can I achieve these kinds of transformations in a smooth way?
I will leave my code below, as well as a codepen link.
Thanks beforehand for your help!
const container = document.querySelector('.container'); const box = document.querySelector('.box'); function animate() { transformBox(); requestAnimationFrame(animate); } function transformBox() { const scrollY = window.scrollY; box.style.transform = `translate3d(0, ${scrollY}px, 0)`; } animate();
* { margin: 0; padding: 0; box-sizing: border-box; } html, body { overscroll-behavior: none; } .container { position: relative; height: 400vh; background-color: #333; } .box { position: absolute; top: calc(50vh - 25px); left: calc(50% - 25px); width: 50px; height: 50px; background-color: white; border-radius: 8px; }
<div class="container"> <div class="box"></div> </div>
-
Animating moving sphere
I want to create an animation of a moving sphere in matplotlib. This is what I've wrote so far
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits import mplot3d from matplotlib import cm from matplotlib import animation import pandas as pd fig = plt.figure(facecolor='black') ax = plt.axes(projection = "3d") u = np.linspace(0, 2*np.pi, 100) v = np.linspace(0, np.pi, 100) r = 4 ax.set_xlim(0, 60) ax.set_ylim(0, 60) ax.set_zlim(0, 60) x0 = r * np.outer(np.cos(u), np.sin(v)) + 10 y0 = r * np.outer(np.sin(u), np.sin(v)) + 10 z0 = r * np.outer(np.ones(np.size(u)), np.cos(v)) + 50 def init(): ax.plot_surface(x0,y0,z0) return fig, def animate(i): ax.plot_surface(x0 + 1, y0 + 1, z0 + 10) return fig, ani = animation. FuncAnimation(fig, animate, init_func = init, frames = 90, interval = 300) plt.show()
Here, I have attempted to move the sphere by (1,1,1) in each new iteration, but it fails to do so.
-
Math.random() in java returning the same double value inside a for loop
I have a java program in which I am calling the following code in a for loop 15 times
Math.random()*1000
. Surprisingly, it is returning the same double value. What could be the
reason for this? -
how to select a random element from an array in shell
arr[0]="" arr[1]="" arr[2]="" arr[3]="" arr[4]="" arr[5]="" arr[6]="" rand=$[$RANDOM % ${#arr[@]}] echo $(date) echo ${arr[$rand]}
can I port a random path from the array to
ls -Ulah [path]
and then loop the randomizer so that it just keeps spouting random files? I seem to be confused with the last 3 lines. Don't hate me, I just started learning yesterday. -
Xpath using using random.randint(2,8) always identifies the first item using Python Selenium
Working on a random question picker from a codechef webpage but the problem is even when i am using random value of i, it always clicks the first question.
Code:
from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium import webdriver from selenium.webdriver.support.ui import Select import time import random PATH = "C:\Program Files (x86)\chromedriver.exe" driver = webdriver.Chrome(PATH) driver.get("https://www.codechef.com/practice?page=0&limit=20&sort_by=difficulty_rating& sort_order=asc&search=&start_rating=0&end_rating=999&topic=&tags=&group=all") driver.execute_script("window.scrollTo(0,document.body.scrollHeight)") time.sleep(3) # element = driver.find_element_by_link_text("Roller Coaster") i = random.randint(2,8) try: item = WebDriverWait(driver, 25).until( EC.presence_of_element_located((By.XPATH, "/html/body/div/div/div/div/div[3]/div/div[2]/div/div[3]/div/div/table/tbody/tr['+str(i)+']/td[2]/div/a")) ) item.click() except: driver.quit()
-
SwiftUI, apply drawGesture only when over Image
I'm try to apply the gesture only when the user is over the Image display not when tapped outside the image.
Any suggestion how I can do? this following code draw also when user tap outside the image.
struct ContentView: View { @StateObject var am = AppManager() @State var switchToTakePicture = false @State var paths: [PathContainer] = [] @State var currentDraggingId = UUID() @State var spikoPic = #imageLiteral(resourceName: "spiko-16.jpeg") @State var centerOFimage = CGSize(width: 0, height: 0) var body: some View { GeometryReader { proxy in ZStack { Image(uiImage: spikoPic) .resizable() .scaledToFit() .position(x: proxy.size.width/2, y: proxy.size.height/2) .background(GeometryReader { Color.clear.preference(key: ViewRectKey.self, value: [$0.frame(in: .global)]) }) .gesture(drawGesture) // not correct ForEach(paths) { container in // draw and set the foreground color of the paths to red container.path .stroke(Color.red, lineWidth: 4) } } .onPreferenceChange(ViewRectKey.self) { rects in print(rects.first ?? .zero) } } } var drawGesture: some Gesture { DragGesture(minimumDistance: 0) .onChanged { value in // The point that the gesture started from let start = value.startLocation // The point that the gesture ended to let end = value.location // the properties of the rectangle to be drawn let rectangle: CGRect = .init(origin: end, size: .init(width: start.x - end.x, height: start.y - end.y)) // create a path for the rectangle let path: Path = .init { path in path.addRect(rectangle) } print("rettangolo = \(rectangle) orig \(rectangle.origin) - height \(rectangle.height) width = \(rectangle.width)") // remove the previous rectangle that was drawen in current // process of drawing paths.removeAll { $0.id == currentDraggingId } // append the new rectangle paths.append(.init(id: currentDraggingId, path: path)) } .onEnded { _ in // renew the dragging id so the app know that the next // drag gesture is drawing a completely new rectangle, // and is not continuing the drawing of the last rectangle currentDraggingId = .init() } } }
i want no box outside
-
How to navigate between NavigationLink while leave a part of main window stay the same in SwiftUI
I would like to navigate between different
NavigationLink
s inNavigationView
while some part of the main window stay the same. For example, I want to make a music app and I want to let the play controller always on top, while I can display different navigation contents (songs page, artists page...) using the rest of the window.Like what's showed in the picture below, I want to keep the red part always there while the blue part changes.
My code would be like below, but it won't work correctly. The
AlwaysStayView()
disappears when I click anyNavigationLink
on sidebar. So, how can I correct it or is there any solution (prefer in SwiftUI, but framework like UIKit would also be OK). I would appreciate it.NavigationView { List { NavigationLink { DiscoverView() } label: { Label("Discover", systemImage: "magnifyingglass") } NavigationLink { SongsView() } label: { Label("Songs", systemImage: "music.note") } NavigationLink { ArtistsView() } label: { Label("Artists", systemImage: "music.mic") } } } .listStyle(SidebarListStyle()) VStack { AlwaysStayView() SongsView() } }
-
SwiftUI NavigationView detail view binding to sheet modal not working
I have a List where the navigationLink destination is a view with a binding property for a user struct. works fine, if in the detail view I create another navigationLink to an edit view with a binding property for the user struct, that will update all the views as expected when the user is modified.
My problem is when I don't use the navigationLink from the detail view and use a sheet modal instead. When I update in the sheet, the master a detail views update, but not the sheet, is there something I'm missing?
NavigationView using NavigationLinks works:
MasterView (List of Users) | (NavigationLink) DetailView(user: $user) this binding works | (NavigationLink) EditView(user: $user) this binding works
NavigationView using NavigationLink to detail, and sheet to edit:
MasterView (List of Users) | (NavigationLink) DetailView(user: $user) this binding works | (sheet) EditView(user: $user) this binding doesn't work
My implementation of opening sheets is as follows:
struct UserDetailView: View { @Binding var user: User @State private var sheetItem: SheetItem? var body: some View { VStack { // content } .toolbar { ToolbarItem(placement: .navigationBarTrailing) { Button(action: { sheetItem = SheetItem(view: AnyView(EditUserView(user: $user))) }) { Text("Edit") } } } .sheet(item: $sheetItem) { view in showSheet(sheet: view) } } } struct SheetItem: Identifiable { var id = UUID() var view: AnyView } func showSheet(sheet: SheetItem) -> some View { return sheet.view }
-
C# Rotate pictureBox , I want to move the bus vertically and I cant, can you help me of coding?
using System.Drawing; using System.Windows.Forms; public partial class Form1 : Form { public bool move_right, move_left, move_up, move_down; public int speed = 10; public int score = 0; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { timer1.Start(); } private void timer1_Tick(object sender, EventArgs e) { if (move_left == true && pictureBox2.Left > 0) { pictureBox2.Left -= speed; } if (move_right == true && pictureBox2.Left < 665) { pictureBox2.Left += speed; } if (move_up == true && pictureBox2.Top > 0) { pictureBox2.Top -= speed; } if (move_down == true && pictureBox2.Top < 366) { pictureBox2.Top += speed; } } private void Form1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Left) { move_left = true; } if (e.KeyCode == Keys.Right) { move_right = true; } if (e.KeyCode == Keys.Up) { move_up = true; } if (e.KeyCode == Keys.Down) { move_down = true; } } private void Form1_KeyUp(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Left) { move_left = false; } if (e.KeyCode == Keys.Right) { move_right = false; } if (e.KeyCode == Keys.Up) { move_up = false; } if (e.KeyCode == Keys.Down) { move_down = false; } } }
-
translate an image after rotation without using library
I try to rotate an image clockwise 45 degree and translate the image -50,-50. Rotation process works fine:(I refer to this page:How do I rotate an image manually without using cv2.getRotationMatrix2D)
import numpy as np import math from scipy import ndimage from PIL import Image # inputs img = ndimage.imread("A.png") rotation_amount_degree = 45 # convert rotation amount to radian rotation_amount_rad = rotation_amount_degree * np.pi / 180.0 # get dimension info height, width, num_channels = img.shape # create output image, for worst case size (45 degree) max_len = int(math.sqrt(height*height + width*width)) rotated_image = np.zeros((max_len, max_len, num_channels)) #rotated_image = np.zeros((img.shape)) rotated_height, rotated_width, _ = rotated_image.shape mid_row = int( (rotated_height+1)/2 ) mid_col = int( (rotated_width+1)/2 ) # for each pixel in output image, find which pixel #it corresponds to in the input image for r in range(rotated_height): for c in range(rotated_width): # apply rotation matrix, the other way y = (r-mid_col)*math.cos(rotation_amount_rad) + (c-mid_row)*math.sin(rotation_amount_rad) x = -(r-mid_col)*math.sin(rotation_amount_rad) + (c-mid_row)*math.cos(rotation_amount_rad) # add offset y += mid_col x += mid_row # get nearest index #a better way is linear interpolation x = round(x) y = round(y) #print(r, " ", c, " corresponds to-> " , y, " ", x) # check if x/y corresponds to a valid pixel in input image if (x >= 0 and y >= 0 and x < width and y < height): rotated_image[r][c][:] = img[y][x][:] # save output image output_image = Image.fromarray(rotated_image.astype("uint8")) output_image.save("rotated_image.png")
However, when I try to translate the image. I edited the above code to this:
if (x >= 0 and y >= 0 and x < width and y < height): rotated_image[r-50][c-50][:] = img[y][x][:]
But I got something like this:
It seems the right and the bottom did not show the right pixel. How could I solve it? Any suggestions would be highly appreciated.