The English word gay comes from Old French gai ‘joyful, happy, pleasant’ (cf. Sp. alegre), which is of uncertain origin. Old Spanish used to have a cognate of this word, namely the word gayo, which was a loanword from Occitan, but it is now archaic, if not obsolete. (This Sp. gayo should not be confused with the homonymous gayo ‘magpie’, an obsolete alternative for urraca, or with gallo ‘rooster’, which is homophonous with gayo in most dialects of Spanish.)
Dubious Germanic etymologies have been proposed for this word, but it is likely related to the Latin word gaudĭum ‘joy, delight’, the source of patrimonial Sp. gozo and its English cognate joy (same meaning), an 11th century loanword from Old French joie (cf. Corominas). The Latin noun gaudĭum was derived from the root gaud‑ of the verb gaudēre ‘to rejoice, take pleasure in’ (principal parts: gaudeō, gaudēre, gāvīsus sum). The related verb in Spanish is gozar ‘to enjoy (oneself)’, which was derived, in Spanish, from the noun gozo, and thus does not descend from Lat. gaudēre. Also derived from the noun gozo in Spanish is its synonym regocijo ‘delight, joy; merriment, rejoicing’, formed with the prefix re‑ and an odd suffix ‑ij‑ (re-goc‑ij‑o). This noun, which first appeared in the mid-16th century, is derived from the verb regocijar, ‘to delight, amuse’, typically used intransitive (reflexively) as regocijarse ‘to rejoice’, which appeared a few decades earlier. Sp. regocijar was probably a calque from Old French rejoir (Mod.Fr. réjouir), a verb derived in this language from the verb jouir that descended from Vulgar Lat. gaudire, from Lat. gaudēre. A lengthened stem of the verb rejoir, namely rejoiss‑, is the source of English rejoice.
The meaning ‘homosexual’ for Eng. gay dates from the mid-20th century and it obviously started as a euphemism (cf. Chapter 6, §6.4.2). This loanword started as an informal (colloquial) word in Spanish, but it has become a regular alternative to the adjective cum noun homosexual, which was a New Latin creation that first appeared in German in the late 19th century. (The parts of this word are Greek homo ‘same’ and Lat. sexual(is) ‘relating to sex’, the adjective derived from Lat. sexus ‘sex, gender’.)
Words for male homosexuals invariantly have acquired pejorative and derogatory connotations throughout history, which is what happened to Sp. maricón, marica, and mariquita, for instance. This is, no doubt, a major reason why the neutral word gay was borrowed from English, where the word does not have negative connotations either (though the English word gay did have the meaning ‘wanton, lewd, lascivious’ (OED) in the 15th century, a meaning that is now obsolete). French, Japanese, and many other languages have borrowed this English word too.